<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>3. Data model &mdash; Python 3.4.3 documentation</title>
    
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.4.3',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.4.3 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python 3.4.3 documentation" href="../index.html" />
    <link rel="up" title="The Python Language Reference" href="index.html" />
    <link rel="next" title="4. Execution model" href="executionmodel.html" />
    <link rel="prev" title="2. Lexical analysis" href="lexical_analysis.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    <script type="text/javascript" src="../_static/version_switch.js"></script>
    
 

  </head>
  <body>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="executionmodel.html" title="4. Execution model"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="lexical_analysis.html" title="2. Lexical analysis"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &raquo;</li>
        <li>
          <span class="version_switcher_placeholder">3.4.3</span>
          <a href="../index.html">Documentation</a> &raquo;
        </li>

          <li><a href="index.html" accesskey="U">The Python Language Reference</a> &raquo;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="data-model">
<span id="datamodel"></span><h1>3. Data model<a class="headerlink" href="#data-model" title="Permalink to this headline">¶</a></h1>
<div class="section" id="objects-values-and-types">
<span id="objects"></span><h2>3.1. Objects, values and types<a class="headerlink" href="#objects-values-and-types" title="Permalink to this headline">¶</a></h2>
<p id="index-0"><em class="dfn">Objects</em> are Python&#8217;s abstraction for data.  All data in a Python program
is represented by objects or by relations between objects. (In a sense, and in
conformance to Von Neumann&#8217;s model of a &#8220;stored program computer,&#8221; code is also
represented by objects.)</p>
<span class="target" id="index-1"></span><p>Every object has an identity, a type and a value.  An object&#8217;s <em>identity</em> never
changes once it has been created; you may think of it as the object&#8217;s address in
memory.  The &#8216;<a class="reference internal" href="expressions.html#is"><tt class="xref std std-keyword docutils literal"><span class="pre">is</span></tt></a>&#8216; operator compares the identity of two objects; the
<a class="reference internal" href="../library/functions.html#id" title="id"><tt class="xref py py-func docutils literal"><span class="pre">id()</span></tt></a> function returns an integer representing its identity.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> For CPython, <tt class="docutils literal"><span class="pre">id(x)</span></tt> is the memory address where <tt class="docutils literal"><span class="pre">x</span></tt> is stored.</p>
</div>
<p>An object&#8217;s type determines the operations that the object supports (e.g., &#8220;does
it have a length?&#8221;) and also defines the possible values for objects of that
type.  The <a class="reference internal" href="../library/functions.html#type" title="type"><tt class="xref py py-func docutils literal"><span class="pre">type()</span></tt></a> function returns an object&#8217;s type (which is an object
itself).  Like its identity, an object&#8217;s <em class="dfn">type</em> is also unchangeable.
<a class="footnote-reference" href="#id4" id="id1">[1]</a></p>
<p>The <em>value</em> of some objects can change.  Objects whose value can
change are said to be <em>mutable</em>; objects whose value is unchangeable once they
are created are called <em>immutable</em>. (The value of an immutable container object
that contains a reference to a mutable object can change when the latter&#8217;s value
is changed; however the container is still considered immutable, because the
collection of objects it contains cannot be changed.  So, immutability is not
strictly the same as having an unchangeable value, it is more subtle.) An
object&#8217;s mutability is determined by its type; for instance, numbers, strings
and tuples are immutable, while dictionaries and lists are mutable.</p>
<p id="index-2">Objects are never explicitly destroyed; however, when they become unreachable
they may be garbage-collected.  An implementation is allowed to postpone garbage
collection or omit it altogether &#8212; it is a matter of implementation quality
how garbage collection is implemented, as long as no objects are collected that
are still reachable.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> CPython currently uses a reference-counting scheme with (optional) delayed
detection of cyclically linked garbage, which collects most objects as soon
as they become unreachable, but is not guaranteed to collect garbage
containing circular references.  See the documentation of the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><tt class="xref py py-mod docutils literal"><span class="pre">gc</span></tt></a>
module for information on controlling the collection of cyclic garbage.
Other implementations act differently and CPython may change.
Do not depend on immediate finalization of objects when they become
unreachable (so you should always close files explicitly).</p>
</div>
<p>Note that the use of the implementation&#8217;s tracing or debugging facilities may
keep objects alive that would normally be collectable. Also note that catching
an exception with a &#8216;<a class="reference internal" href="compound_stmts.html#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a>...<a class="reference internal" href="compound_stmts.html#except"><tt class="xref std std-keyword docutils literal"><span class="pre">except</span></tt></a>&#8216; statement may keep
objects alive.</p>
<p>Some objects contain references to &#8220;external&#8221; resources such as open files or
windows.  It is understood that these resources are freed when the object is
garbage-collected, but since garbage collection is not guaranteed to happen,
such objects also provide an explicit way to release the external resource,
usually a <tt class="xref py py-meth docutils literal"><span class="pre">close()</span></tt> method. Programs are strongly recommended to explicitly
close such objects.  The &#8216;<a class="reference internal" href="compound_stmts.html#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a>...<a class="reference internal" href="compound_stmts.html#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a>&#8216; statement
and the &#8216;<a class="reference internal" href="compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statement provide convenient ways to do this.</p>
<p id="index-3">Some objects contain references to other objects; these are called <em>containers</em>.
Examples of containers are tuples, lists and dictionaries.  The references are
part of a container&#8217;s value.  In most cases, when we talk about the value of a
container, we imply the values, not the identities of the contained objects;
however, when we talk about the mutability of a container, only the identities
of the immediately contained objects are implied.  So, if an immutable container
(like a tuple) contains a reference to a mutable object, its value changes if
that mutable object is changed.</p>
<p>Types affect almost all aspects of object behavior.  Even the importance of
object identity is affected in some sense: for immutable types, operations that
compute new values may actually return a reference to any existing object with
the same type and value, while for mutable objects this is not allowed.  E.g.,
after <tt class="docutils literal"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">1;</span> <span class="pre">b</span> <span class="pre">=</span> <span class="pre">1</span></tt>, <tt class="docutils literal"><span class="pre">a</span></tt> and <tt class="docutils literal"><span class="pre">b</span></tt> may or may not refer to the same object
with the value one, depending on the implementation, but after <tt class="docutils literal"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">[];</span> <span class="pre">d</span> <span class="pre">=</span>
<span class="pre">[]</span></tt>, <tt class="docutils literal"><span class="pre">c</span></tt> and <tt class="docutils literal"><span class="pre">d</span></tt> are guaranteed to refer to two different, unique, newly
created empty lists. (Note that <tt class="docutils literal"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">d</span> <span class="pre">=</span> <span class="pre">[]</span></tt> assigns the same object to both
<tt class="docutils literal"><span class="pre">c</span></tt> and <tt class="docutils literal"><span class="pre">d</span></tt>.)</p>
</div>
<div class="section" id="the-standard-type-hierarchy">
<span id="types"></span><h2>3.2. The standard type hierarchy<a class="headerlink" href="#the-standard-type-hierarchy" title="Permalink to this headline">¶</a></h2>
<p id="index-4">Below is a list of the types that are built into Python.  Extension modules
(written in C, Java, or other languages, depending on the implementation) can
define additional types.  Future versions of Python may add types to the type
hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.),
although such additions will often be provided via the standard library instead.</p>
<p id="index-5">Some of the type descriptions below contain a paragraph listing &#8216;special
attributes.&#8217;  These are attributes that provide access to the implementation and
are not intended for general use.  Their definition may change in the future.</p>
<dl class="docutils">
<dt>None</dt>
<dd><p class="first last" id="index-6">This type has a single value.  There is a single object with this value. This
object is accessed through the built-in name <tt class="docutils literal"><span class="pre">None</span></tt>. It is used to signify the
absence of a value in many situations, e.g., it is returned from functions that
don&#8217;t explicitly return anything. Its truth value is false.</p>
</dd>
<dt>NotImplemented</dt>
<dd><p class="first" id="index-7">This type has a single value.  There is a single object with this value. This
object is accessed through the built-in name <tt class="docutils literal"><span class="pre">NotImplemented</span></tt>. Numeric methods
and rich comparison methods should return this value if they do not implement the
operation for the operands provided.  (The interpreter will then try the
reflected operation, or some other fallback, depending on the operator.)  Its
truth value is true.</p>
<p class="last">See
<a class="reference internal" href="../library/numbers.html#implementing-the-arithmetic-operations"><em>Implementing the arithmetic operations</em></a>
for more details.</p>
</dd>
<dt>Ellipsis</dt>
<dd><p class="first last" id="index-8">This type has a single value.  There is a single object with this value. This
object is accessed through the literal <tt class="docutils literal"><span class="pre">...</span></tt> or the built-in name
<tt class="docutils literal"><span class="pre">Ellipsis</span></tt>.  Its truth value is true.</p>
</dd>
<dt><a class="reference internal" href="../library/numbers.html#numbers.Number" title="numbers.Number"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Number</span></tt></a></dt>
<dd><p class="first" id="index-9">These are created by numeric literals and returned as results by arithmetic
operators and arithmetic built-in functions.  Numeric objects are immutable;
once created their value never changes.  Python numbers are of course strongly
related to mathematical numbers, but subject to the limitations of numerical
representation in computers.</p>
<p>Python distinguishes between integers, floating point numbers, and complex
numbers:</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../library/numbers.html#numbers.Integral" title="numbers.Integral"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Integral</span></tt></a></dt>
<dd><p class="first" id="index-10">These represent elements from the mathematical set of integers (positive and
negative).</p>
<p>There are two types of integers:</p>
<p>Integers (<a class="reference internal" href="../library/functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a>)</p>
<blockquote>
<div>These represent numbers in an unlimited range, subject to available (virtual)
memory only.  For the purpose of shift and mask operations, a binary
representation is assumed, and negative numbers are represented in a variant of
2&#8217;s complement which gives the illusion of an infinite string of sign bits
extending to the left.</div></blockquote>
<dl class="docutils">
<dt>Booleans (<a class="reference internal" href="../library/functions.html#bool" title="bool"><tt class="xref py py-class docutils literal"><span class="pre">bool</span></tt></a>)</dt>
<dd><p class="first last" id="index-11">These represent the truth values False and True.  The two objects representing
the values <tt class="docutils literal"><span class="pre">False</span></tt> and <tt class="docutils literal"><span class="pre">True</span></tt> are the only Boolean objects. The Boolean type is a
subtype of the integer type, and Boolean values behave like the values 0 and 1,
respectively, in almost all contexts, the exception being that when converted to
a string, the strings <tt class="docutils literal"><span class="pre">&quot;False&quot;</span></tt> or <tt class="docutils literal"><span class="pre">&quot;True&quot;</span></tt> are returned, respectively.</p>
</dd>
</dl>
<p class="last" id="index-12">The rules for integer representation are intended to give the most meaningful
interpretation of shift and mask operations involving negative integers.</p>
</dd>
<dt><a class="reference internal" href="../library/numbers.html#numbers.Real" title="numbers.Real"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Real</span></tt></a> (<a class="reference internal" href="../library/functions.html#float" title="float"><tt class="xref py py-class docutils literal"><span class="pre">float</span></tt></a>)</dt>
<dd><p class="first last" id="index-13">These represent machine-level double precision floating point numbers. You are
at the mercy of the underlying machine architecture (and C or Java
implementation) for the accepted range and handling of overflow. Python does not
support single-precision floating point numbers; the savings in processor and
memory usage that are usually the reason for using these are dwarfed by the
overhead of using objects in Python, so there is no reason to complicate the
language with two kinds of floating point numbers.</p>
</dd>
<dt><a class="reference internal" href="../library/numbers.html#numbers.Complex" title="numbers.Complex"><tt class="xref py py-class docutils literal"><span class="pre">numbers.Complex</span></tt></a> (<a class="reference internal" href="../library/functions.html#complex" title="complex"><tt class="xref py py-class docutils literal"><span class="pre">complex</span></tt></a>)</dt>
<dd><p class="first last" id="index-14">These represent complex numbers as a pair of machine-level double precision
floating point numbers.  The same caveats apply as for floating point numbers.
The real and imaginary parts of a complex number <tt class="docutils literal"><span class="pre">z</span></tt> can be retrieved through
the read-only attributes <tt class="docutils literal"><span class="pre">z.real</span></tt> and <tt class="docutils literal"><span class="pre">z.imag</span></tt>.</p>
</dd>
</dl>
</dd>
<dt>Sequences</dt>
<dd><p class="first" id="index-15">These represent finite ordered sets indexed by non-negative numbers. The
built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><tt class="xref py py-func docutils literal"><span class="pre">len()</span></tt></a> returns the number of items of a sequence. When
the length of a sequence is <em>n</em>, the index set contains the numbers 0, 1,
..., <em>n</em>-1.  Item <em>i</em> of sequence <em>a</em> is selected by <tt class="docutils literal"><span class="pre">a[i]</span></tt>.</p>
<p id="index-16">Sequences also support slicing: <tt class="docutils literal"><span class="pre">a[i:j]</span></tt> selects all items with index <em>k</em> such
that <em>i</em> <tt class="docutils literal"><span class="pre">&lt;=</span></tt> <em>k</em> <tt class="docutils literal"><span class="pre">&lt;</span></tt> <em>j</em>.  When used as an expression, a slice is a
sequence of the same type.  This implies that the index set is renumbered so
that it starts at 0.</p>
<p>Some sequences also support &#8220;extended slicing&#8221; with a third &#8220;step&#8221; parameter:
<tt class="docutils literal"><span class="pre">a[i:j:k]</span></tt> selects all items of <em>a</em> with index <em>x</em> where <tt class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">i</span> <span class="pre">+</span> <span class="pre">n*k</span></tt>, <em>n</em>
<tt class="docutils literal"><span class="pre">&gt;=</span></tt> <tt class="docutils literal"><span class="pre">0</span></tt> and <em>i</em> <tt class="docutils literal"><span class="pre">&lt;=</span></tt> <em>x</em> <tt class="docutils literal"><span class="pre">&lt;</span></tt> <em>j</em>.</p>
<p>Sequences are distinguished according to their mutability:</p>
<dl class="last docutils">
<dt>Immutable sequences</dt>
<dd><p class="first" id="index-17">An object of an immutable sequence type cannot change once it is created.  (If
the object contains references to other objects, these other objects may be
mutable and may be changed; however, the collection of objects directly
referenced by an immutable object cannot change.)</p>
<p>The following types are immutable sequences:</p>
<dl class="last docutils" id="index-18">
<dt>Strings</dt>
<dd><p class="first last" id="index-19">A string is a sequence of values that represent Unicode code points.
All the code points in the range <tt class="docutils literal"><span class="pre">U+0000</span> <span class="pre">-</span> <span class="pre">U+10FFFF</span></tt> can be
represented in a string.  Python doesn&#8217;t have a <tt class="xref c c-type docutils literal"><span class="pre">char</span></tt> type;
instead, every code point in the string is represented as a string
object with length <tt class="docutils literal"><span class="pre">1</span></tt>.  The built-in function <a class="reference internal" href="../library/functions.html#ord" title="ord"><tt class="xref py py-func docutils literal"><span class="pre">ord()</span></tt></a>
converts a code point from its string form to an integer in the
range <tt class="docutils literal"><span class="pre">0</span> <span class="pre">-</span> <span class="pre">10FFFF</span></tt>; <a class="reference internal" href="../library/functions.html#chr" title="chr"><tt class="xref py py-func docutils literal"><span class="pre">chr()</span></tt></a> converts an integer in the range
<tt class="docutils literal"><span class="pre">0</span> <span class="pre">-</span> <span class="pre">10FFFF</span></tt> to the corresponding length <tt class="docutils literal"><span class="pre">1</span></tt> string object.
<a class="reference internal" href="../library/stdtypes.html#str.encode" title="str.encode"><tt class="xref py py-meth docutils literal"><span class="pre">str.encode()</span></tt></a> can be used to convert a <a class="reference internal" href="../library/stdtypes.html#str" title="str"><tt class="xref py py-class docutils literal"><span class="pre">str</span></tt></a> to
<a class="reference internal" href="../library/functions.html#bytes" title="bytes"><tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt></a> using the given text encoding, and
<a class="reference internal" href="../library/stdtypes.html#bytes.decode" title="bytes.decode"><tt class="xref py py-meth docutils literal"><span class="pre">bytes.decode()</span></tt></a> can be used to achieve the opposite.</p>
</dd>
<dt>Tuples</dt>
<dd><p class="first last" id="index-20">The items of a tuple are arbitrary Python objects. Tuples of two or
more items are formed by comma-separated lists of expressions.  A tuple
of one item (a &#8216;singleton&#8217;) can be formed by affixing a comma to an
expression (an expression by itself does not create a tuple, since
parentheses must be usable for grouping of expressions).  An empty
tuple can be formed by an empty pair of parentheses.</p>
</dd>
<dt>Bytes</dt>
<dd><p class="first last" id="index-21">A bytes object is an immutable array.  The items are 8-bit bytes,
represented by integers in the range 0 &lt;= x &lt; 256.  Bytes literals
(like <tt class="docutils literal"><span class="pre">b'abc'</span></tt>) and the built-in function <a class="reference internal" href="../library/functions.html#bytes" title="bytes"><tt class="xref py py-func docutils literal"><span class="pre">bytes()</span></tt></a> can be used to
construct bytes objects.  Also, bytes objects can be decoded to strings
via the <a class="reference internal" href="../library/stdtypes.html#bytes.decode" title="bytes.decode"><tt class="xref py py-meth docutils literal"><span class="pre">decode()</span></tt></a> method.</p>
</dd>
</dl>
</dd>
<dt>Mutable sequences</dt>
<dd><p class="first" id="index-22">Mutable sequences can be changed after they are created.  The subscription and
slicing notations can be used as the target of assignment and <a class="reference internal" href="simple_stmts.html#del"><tt class="xref std std-keyword docutils literal"><span class="pre">del</span></tt></a>
(delete) statements.</p>
<p>There are currently two intrinsic mutable sequence types:</p>
<dl class="docutils">
<dt>Lists</dt>
<dd><p class="first last" id="index-23">The items of a list are arbitrary Python objects.  Lists are formed by
placing a comma-separated list of expressions in square brackets. (Note
that there are no special cases needed to form lists of length 0 or 1.)</p>
</dd>
<dt>Byte Arrays</dt>
<dd><p class="first last" id="index-24">A bytearray object is a mutable array. They are created by the built-in
<a class="reference internal" href="../library/functions.html#bytearray" title="bytearray"><tt class="xref py py-func docutils literal"><span class="pre">bytearray()</span></tt></a> constructor.  Aside from being mutable (and hence
unhashable), byte arrays otherwise provide the same interface and
functionality as immutable bytes objects.</p>
</dd>
</dl>
<p class="last" id="index-25">The extension module <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><tt class="xref py py-mod docutils literal"><span class="pre">array</span></tt></a> provides an additional example of a
mutable sequence type, as does the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><tt class="xref py py-mod docutils literal"><span class="pre">collections</span></tt></a> module.</p>
</dd>
</dl>
</dd>
<dt>Set types</dt>
<dd><p class="first" id="index-26">These represent unordered, finite sets of unique, immutable objects. As such,
they cannot be indexed by any subscript. However, they can be iterated over, and
the built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><tt class="xref py py-func docutils literal"><span class="pre">len()</span></tt></a> returns the number of items in a set. Common
uses for sets are fast membership testing, removing duplicates from a sequence,
and computing mathematical operations such as intersection, union, difference,
and symmetric difference.</p>
<p>For set elements, the same immutability rules apply as for dictionary keys. Note
that numeric types obey the normal rules for numeric comparison: if two numbers
compare equal (e.g., <tt class="docutils literal"><span class="pre">1</span></tt> and <tt class="docutils literal"><span class="pre">1.0</span></tt>), only one of them can be contained in a
set.</p>
<p>There are currently two intrinsic set types:</p>
<dl class="last docutils">
<dt>Sets</dt>
<dd><p class="first last" id="index-27">These represent a mutable set. They are created by the built-in <a class="reference internal" href="../library/stdtypes.html#set" title="set"><tt class="xref py py-func docutils literal"><span class="pre">set()</span></tt></a>
constructor and can be modified afterwards by several methods, such as
<a class="reference internal" href="../library/stdtypes.html#set.add" title="set.add"><tt class="xref py py-meth docutils literal"><span class="pre">add()</span></tt></a>.</p>
</dd>
<dt>Frozen sets</dt>
<dd><p class="first last" id="index-28">These represent an immutable set.  They are created by the built-in
<a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><tt class="xref py py-func docutils literal"><span class="pre">frozenset()</span></tt></a> constructor.  As a frozenset is immutable and
<a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a>, it can be used again as an element of another set, or as
a dictionary key.</p>
</dd>
</dl>
</dd>
<dt>Mappings</dt>
<dd><p class="first" id="index-29">These represent finite sets of objects indexed by arbitrary index sets. The
subscript notation <tt class="docutils literal"><span class="pre">a[k]</span></tt> selects the item indexed by <tt class="docutils literal"><span class="pre">k</span></tt> from the mapping
<tt class="docutils literal"><span class="pre">a</span></tt>; this can be used in expressions and as the target of assignments or
<a class="reference internal" href="simple_stmts.html#del"><tt class="xref std std-keyword docutils literal"><span class="pre">del</span></tt></a> statements. The built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><tt class="xref py py-func docutils literal"><span class="pre">len()</span></tt></a> returns the number
of items in a mapping.</p>
<p>There is currently a single intrinsic mapping type:</p>
<dl class="last docutils">
<dt>Dictionaries</dt>
<dd><p class="first" id="index-30">These represent finite sets of objects indexed by nearly arbitrary values.  The
only types of values not acceptable as keys are values containing lists or
dictionaries or other mutable types that are compared by value rather than by
object identity, the reason being that the efficient implementation of
dictionaries requires a key&#8217;s hash value to remain constant. Numeric types used
for keys obey the normal rules for numeric comparison: if two numbers compare
equal (e.g., <tt class="docutils literal"><span class="pre">1</span></tt> and <tt class="docutils literal"><span class="pre">1.0</span></tt>) then they can be used interchangeably to index
the same dictionary entry.</p>
<p>Dictionaries are mutable; they can be created by the <tt class="docutils literal"><span class="pre">{...}</span></tt> notation (see
section <a class="reference internal" href="expressions.html#dict"><em>Dictionary displays</em></a>).</p>
<p class="last" id="index-31">The extension modules <a class="reference internal" href="../library/dbm.html#module-dbm.ndbm" title="dbm.ndbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><tt class="xref py py-mod docutils literal"><span class="pre">dbm.ndbm</span></tt></a> and <a class="reference internal" href="../library/dbm.html#module-dbm.gnu" title="dbm.gnu: GNU's reinterpretation of dbm. (Unix)"><tt class="xref py py-mod docutils literal"><span class="pre">dbm.gnu</span></tt></a> provide
additional examples of mapping types, as does the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><tt class="xref py py-mod docutils literal"><span class="pre">collections</span></tt></a>
module.</p>
</dd>
</dl>
</dd>
<dt>Callable types</dt>
<dd><p class="first" id="index-32">These are the types to which the function call operation (see section
<a class="reference internal" href="expressions.html#calls"><em>Calls</em></a>) can be applied:</p>
<dl class="last docutils">
<dt>User-defined functions</dt>
<dd><p class="first" id="index-33">A user-defined function object is created by a function definition (see
section <a class="reference internal" href="compound_stmts.html#function"><em>Function definitions</em></a>).  It should be called with an argument list
containing the same number of items as the function&#8217;s formal parameter
list.</p>
<p>Special attributes:</p>
<table border="1" class="docutils">
<colgroup>
<col width="37%" />
<col width="46%" />
<col width="16%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Attribute</th>
<th class="head">Meaning</th>
<th class="head">&nbsp;</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><tt class="xref py py-attr docutils literal"><span class="pre">__doc__</span></tt></td>
<td>The function&#8217;s documentation
string, or <tt class="docutils literal"><span class="pre">None</span></tt> if
unavailable; not inherited by
subclasses</td>
<td>Writable</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="import.html#__name__" title="__name__"><tt class="xref py py-attr docutils literal"><span class="pre">__name__</span></tt></a></td>
<td>The function&#8217;s name</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><tt class="xref py py-attr docutils literal"><span class="pre">__qualname__</span></tt></td>
<td><p class="first">The function&#8217;s
<a class="reference internal" href="../glossary.html#term-qualified-name"><em class="xref std std-term">qualified name</em></a></p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 3.3.</span></p>
</div>
</td>
<td>Writable</td>
</tr>
<tr class="row-odd"><td><tt class="xref py py-attr docutils literal"><span class="pre">__module__</span></tt></td>
<td>The name of the module the
function was defined in, or
<tt class="docutils literal"><span class="pre">None</span></tt> if unavailable.</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><tt class="xref py py-attr docutils literal"><span class="pre">__defaults__</span></tt></td>
<td>A tuple containing default
argument values for those
arguments that have defaults,
or <tt class="docutils literal"><span class="pre">None</span></tt> if no arguments
have a default value</td>
<td>Writable</td>
</tr>
<tr class="row-odd"><td><tt class="xref py py-attr docutils literal"><span class="pre">__code__</span></tt></td>
<td>The code object representing
the compiled function body.</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><tt class="xref py py-attr docutils literal"><span class="pre">__globals__</span></tt></td>
<td>A reference to the dictionary
that holds the function&#8217;s
global variables &#8212; the
global namespace of the
module in which the function
was defined.</td>
<td>Read-only</td>
</tr>
<tr class="row-odd"><td><tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt></td>
<td>The namespace supporting
arbitrary function
attributes.</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><tt class="xref py py-attr docutils literal"><span class="pre">__closure__</span></tt></td>
<td><tt class="docutils literal"><span class="pre">None</span></tt> or a tuple of cells
that contain bindings for the
function&#8217;s free variables.</td>
<td>Read-only</td>
</tr>
<tr class="row-odd"><td><tt class="xref py py-attr docutils literal"><span class="pre">__annotations__</span></tt></td>
<td>A dict containing annotations
of parameters.  The keys of
the dict are the parameter
names, and <tt class="docutils literal"><span class="pre">'return'</span></tt> for
the return annotation, if
provided.</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><tt class="xref py py-attr docutils literal"><span class="pre">__kwdefaults__</span></tt></td>
<td>A dict containing defaults
for keyword-only parameters.</td>
<td>Writable</td>
</tr>
</tbody>
</table>
<p>Most of the attributes labelled &#8220;Writable&#8221; check the type of the assigned value.</p>
<p>Function objects also support getting and setting arbitrary attributes, which
can be used, for example, to attach metadata to functions.  Regular attribute
dot-notation is used to get and set such attributes. <em>Note that the current
implementation only supports function attributes on user-defined functions.
Function attributes on built-in functions may be supported in the future.</em></p>
<p class="last">Additional information about a function&#8217;s definition can be retrieved from its
code object; see the description of internal types below.</p>
</dd>
<dt>Instance methods</dt>
<dd><p class="first" id="index-35">An instance method object combines a class, a class instance and any
callable object (normally a user-defined function).</p>
<p id="index-36">Special read-only attributes: <tt class="xref py py-attr docutils literal"><span class="pre">__self__</span></tt> is the class instance object,
<tt class="xref py py-attr docutils literal"><span class="pre">__func__</span></tt> is the function object; <tt class="xref py py-attr docutils literal"><span class="pre">__doc__</span></tt> is the method&#8217;s
documentation (same as <tt class="docutils literal"><span class="pre">__func__.__doc__</span></tt>); <a class="reference internal" href="import.html#__name__" title="__name__"><tt class="xref py py-attr docutils literal"><span class="pre">__name__</span></tt></a> is the
method name (same as <tt class="docutils literal"><span class="pre">__func__.__name__</span></tt>); <tt class="xref py py-attr docutils literal"><span class="pre">__module__</span></tt> is the
name of the module the method was defined in, or <tt class="docutils literal"><span class="pre">None</span></tt> if unavailable.</p>
<p>Methods also support accessing (but not setting) the arbitrary function
attributes on the underlying function object.</p>
<p>User-defined method objects may be created when getting an attribute of a
class (perhaps via an instance of that class), if that attribute is a
user-defined function object or a class method object.</p>
<p>When an instance method object is created by retrieving a user-defined
function object from a class via one of its instances, its
<tt class="xref py py-attr docutils literal"><span class="pre">__self__</span></tt> attribute is the instance, and the method object is said
to be bound.  The new method&#8217;s <tt class="xref py py-attr docutils literal"><span class="pre">__func__</span></tt> attribute is the original
function object.</p>
<p>When a user-defined method object is created by retrieving another method
object from a class or instance, the behaviour is the same as for a
function object, except that the <tt class="xref py py-attr docutils literal"><span class="pre">__func__</span></tt> attribute of the new
instance is not the original method object but its <tt class="xref py py-attr docutils literal"><span class="pre">__func__</span></tt>
attribute.</p>
<p>When an instance method object is created by retrieving a class method
object from a class or instance, its <tt class="xref py py-attr docutils literal"><span class="pre">__self__</span></tt> attribute is the
class itself, and its <tt class="xref py py-attr docutils literal"><span class="pre">__func__</span></tt> attribute is the function object
underlying the class method.</p>
<p>When an instance method object is called, the underlying function
(<tt class="xref py py-attr docutils literal"><span class="pre">__func__</span></tt>) is called, inserting the class instance
(<tt class="xref py py-attr docutils literal"><span class="pre">__self__</span></tt>) in front of the argument list.  For instance, when
<tt class="xref py py-class docutils literal"><span class="pre">C</span></tt> is a class which contains a definition for a function
<tt class="xref py py-meth docutils literal"><span class="pre">f()</span></tt>, and <tt class="docutils literal"><span class="pre">x</span></tt> is an instance of <tt class="xref py py-class docutils literal"><span class="pre">C</span></tt>, calling <tt class="docutils literal"><span class="pre">x.f(1)</span></tt> is
equivalent to calling <tt class="docutils literal"><span class="pre">C.f(x,</span> <span class="pre">1)</span></tt>.</p>
<p>When an instance method object is derived from a class method object, the
&#8220;class instance&#8221; stored in <tt class="xref py py-attr docutils literal"><span class="pre">__self__</span></tt> will actually be the class
itself, so that calling either <tt class="docutils literal"><span class="pre">x.f(1)</span></tt> or <tt class="docutils literal"><span class="pre">C.f(1)</span></tt> is equivalent to
calling <tt class="docutils literal"><span class="pre">f(C,1)</span></tt> where <tt class="docutils literal"><span class="pre">f</span></tt> is the underlying function.</p>
<p class="last">Note that the transformation from function object to instance method
object happens each time the attribute is retrieved from the instance.  In
some cases, a fruitful optimization is to assign the attribute to a local
variable and call that local variable. Also notice that this
transformation only happens for user-defined functions; other callable
objects (and all non-callable objects) are retrieved without
transformation.  It is also important to note that user-defined functions
which are attributes of a class instance are not converted to bound
methods; this <em>only</em> happens when the function is an attribute of the
class.</p>
</dd>
<dt>Generator functions</dt>
<dd><p class="first last" id="index-37">A function or method which uses the <a class="reference internal" href="simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> statement (see section
<a class="reference internal" href="simple_stmts.html#yield"><em>The yield statement</em></a>) is called a <em class="dfn">generator function</em>.  Such a function, when
called, always returns an iterator object which can be used to execute the
body of the function:  calling the iterator&#8217;s <a class="reference internal" href="../library/stdtypes.html#iterator.__next__" title="iterator.__next__"><tt class="xref py py-meth docutils literal"><span class="pre">iterator.__next__()</span></tt></a>
method will cause the function to execute until it provides a value
using the <a class="reference internal" href="simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> statement.  When the function executes a
<a class="reference internal" href="simple_stmts.html#return"><tt class="xref std std-keyword docutils literal"><span class="pre">return</span></tt></a> statement or falls off the end, a <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><tt class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></tt></a>
exception is raised and the iterator will have reached the end of the set of
values to be returned.</p>
</dd>
<dt>Built-in functions</dt>
<dd><p class="first last" id="index-38">A built-in function object is a wrapper around a C function.  Examples of
built-in functions are <a class="reference internal" href="../library/functions.html#len" title="len"><tt class="xref py py-func docutils literal"><span class="pre">len()</span></tt></a> and <a class="reference internal" href="../library/math.html#math.sin" title="math.sin"><tt class="xref py py-func docutils literal"><span class="pre">math.sin()</span></tt></a> (<a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><tt class="xref py py-mod docutils literal"><span class="pre">math</span></tt></a> is a
standard built-in module). The number and type of the arguments are
determined by the C function. Special read-only attributes:
<tt class="xref py py-attr docutils literal"><span class="pre">__doc__</span></tt> is the function&#8217;s documentation string, or <tt class="docutils literal"><span class="pre">None</span></tt> if
unavailable; <a class="reference internal" href="import.html#__name__" title="__name__"><tt class="xref py py-attr docutils literal"><span class="pre">__name__</span></tt></a> is the function&#8217;s name; <tt class="xref py py-attr docutils literal"><span class="pre">__self__</span></tt> is
set to <tt class="docutils literal"><span class="pre">None</span></tt> (but see the next item); <tt class="xref py py-attr docutils literal"><span class="pre">__module__</span></tt> is the name of
the module the function was defined in or <tt class="docutils literal"><span class="pre">None</span></tt> if unavailable.</p>
</dd>
<dt>Built-in methods</dt>
<dd><p class="first last" id="index-39">This is really a different disguise of a built-in function, this time containing
an object passed to the C function as an implicit extra argument.  An example of
a built-in method is <tt class="docutils literal"><span class="pre">alist.append()</span></tt>, assuming <em>alist</em> is a list object. In
this case, the special read-only attribute <tt class="xref py py-attr docutils literal"><span class="pre">__self__</span></tt> is set to the object
denoted by <em>alist</em>.</p>
</dd>
<dt>Classes</dt>
<dd>Classes are callable.  These objects normally act as factories for new
instances of themselves, but variations are possible for class types that
override <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a>.  The arguments of the call are passed to
<a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> and, in the typical case, to <a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> to
initialize the new instance.</dd>
<dt>Class Instances</dt>
<dd>Instances of arbitrary classes can be made callable by defining a
<a class="reference internal" href="#object.__call__" title="object.__call__"><tt class="xref py py-meth docutils literal"><span class="pre">__call__()</span></tt></a> method in their class.</dd>
</dl>
</dd>
<dt>Modules</dt>
<dd><p class="first" id="index-40">Modules are a basic organizational unit of Python code, and are created by
the <a class="reference internal" href="import.html#importsystem"><em>import system</em></a> as invoked either by the
<a class="reference internal" href="simple_stmts.html#import"><tt class="xref std std-keyword docutils literal"><span class="pre">import</span></tt></a> statement (see <a class="reference internal" href="simple_stmts.html#import"><tt class="xref std std-keyword docutils literal"><span class="pre">import</span></tt></a>), or by calling
functions such as <a class="reference internal" href="../library/importlib.html#importlib.import_module" title="importlib.import_module"><tt class="xref py py-func docutils literal"><span class="pre">importlib.import_module()</span></tt></a> and built-in
<a class="reference internal" href="../library/functions.html#__import__" title="__import__"><tt class="xref py py-func docutils literal"><span class="pre">__import__()</span></tt></a>.  A module object has a namespace implemented by a
dictionary object (this is the dictionary referenced by the <tt class="docutils literal"><span class="pre">__globals__</span></tt>
attribute of functions defined in the module).  Attribute references are
translated to lookups in this dictionary, e.g., <tt class="docutils literal"><span class="pre">m.x</span></tt> is equivalent to
<tt class="docutils literal"><span class="pre">m.__dict__[&quot;x&quot;]</span></tt>. A module object does not contain the code object used
to initialize the module (since it isn&#8217;t needed once the initialization is
done).</p>
<p>Attribute assignment updates the module&#8217;s namespace dictionary, e.g.,
<tt class="docutils literal"><span class="pre">m.x</span> <span class="pre">=</span> <span class="pre">1</span></tt> is equivalent to <tt class="docutils literal"><span class="pre">m.__dict__[&quot;x&quot;]</span> <span class="pre">=</span> <span class="pre">1</span></tt>.</p>
<p id="index-41">Special read-only attribute: <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt> is the module&#8217;s namespace as a
dictionary object.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> Because of the way CPython clears module dictionaries, the module
dictionary will be cleared when the module falls out of scope even if the
dictionary still has live references.  To avoid this, copy the dictionary
or keep the module around while using its dictionary directly.</p>
</div>
<p class="last" id="index-42">Predefined (writable) attributes: <a class="reference internal" href="import.html#__name__" title="__name__"><tt class="xref py py-attr docutils literal"><span class="pre">__name__</span></tt></a> is the module&#8217;s name;
<tt class="xref py py-attr docutils literal"><span class="pre">__doc__</span></tt> is the module&#8217;s documentation string, or <tt class="docutils literal"><span class="pre">None</span></tt> if
unavailable; <a class="reference internal" href="import.html#__file__" title="__file__"><tt class="xref py py-attr docutils literal"><span class="pre">__file__</span></tt></a> is the pathname of the file from which the
module was loaded, if it was loaded from a file. The <a class="reference internal" href="import.html#__file__" title="__file__"><tt class="xref py py-attr docutils literal"><span class="pre">__file__</span></tt></a>
attribute may be missing for certain types of modules, such as C modules
that are statically linked into the interpreter; for extension modules
loaded dynamically from a shared library, it is the pathname of the shared
library file.</p>
</dd>
<dt>Custom classes</dt>
<dd><p class="first">Custom class types are typically created by class definitions (see section
<a class="reference internal" href="compound_stmts.html#class"><em>Class definitions</em></a>).  A class has a namespace implemented by a dictionary object.
Class attribute references are translated to lookups in this dictionary, e.g.,
<tt class="docutils literal"><span class="pre">C.x</span></tt> is translated to <tt class="docutils literal"><span class="pre">C.__dict__[&quot;x&quot;]</span></tt> (although there are a number of
hooks which allow for other means of locating attributes). When the attribute
name is not found there, the attribute search continues in the base classes.
This search of the base classes uses the C3 method resolution order which
behaves correctly even in the presence of &#8216;diamond&#8217; inheritance structures
where there are multiple inheritance paths leading back to a common ancestor.
Additional details on the C3 MRO used by Python can be found in the
documentation accompanying the 2.3 release at
<a class="reference external" href="https://www.python.org/download/releases/2.3/mro/">https://www.python.org/download/releases/2.3/mro/</a>.</p>
<p id="index-43">When a class attribute reference (for class <tt class="xref py py-class docutils literal"><span class="pre">C</span></tt>, say) would yield a
class method object, it is transformed into an instance method object whose
<tt class="xref py py-attr docutils literal"><span class="pre">__self__</span></tt> attributes is <tt class="xref py py-class docutils literal"><span class="pre">C</span></tt>.  When it would yield a static
method object, it is transformed into the object wrapped by the static method
object. See section <a class="reference internal" href="#descriptors"><em>Implementing Descriptors</em></a> for another way in which attributes
retrieved from a class may differ from those actually contained in its
<tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt>.</p>
<p id="index-44">Class attribute assignments update the class&#8217;s dictionary, never the dictionary
of a base class.</p>
<p id="index-45">A class object can be called (see above) to yield a class instance (see below).</p>
<p class="last" id="index-46">Special attributes: <a class="reference internal" href="import.html#__name__" title="__name__"><tt class="xref py py-attr docutils literal"><span class="pre">__name__</span></tt></a> is the class name; <tt class="xref py py-attr docutils literal"><span class="pre">__module__</span></tt> is
the module name in which the class was defined; <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt> is the
dictionary containing the class&#8217;s namespace; <a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><tt class="xref py py-attr docutils literal"><span class="pre">__bases__</span></tt></a> is a
tuple (possibly empty or a singleton) containing the base classes, in the
order of their occurrence in the base class list; <tt class="xref py py-attr docutils literal"><span class="pre">__doc__</span></tt> is the
class&#8217;s documentation string, or None if undefined.</p>
</dd>
<dt>Class instances</dt>
<dd><p class="first" id="index-47">A class instance is created by calling a class object (see above).  A class
instance has a namespace implemented as a dictionary which is the first place
in which attribute references are searched.  When an attribute is not found
there, and the instance&#8217;s class has an attribute by that name, the search
continues with the class attributes.  If a class attribute is found that is a
user-defined function object, it is transformed into an instance method
object whose <tt class="xref py py-attr docutils literal"><span class="pre">__self__</span></tt> attribute is the instance.  Static method and
class method objects are also transformed; see above under &#8220;Classes&#8221;.  See
section <a class="reference internal" href="#descriptors"><em>Implementing Descriptors</em></a> for another way in which attributes of a class
retrieved via its instances may differ from the objects actually stored in
the class&#8217;s <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt>.  If no class attribute is found, and the
object&#8217;s class has a <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></tt></a> method, that is called to satisfy
the lookup.</p>
<p id="index-48">Attribute assignments and deletions update the instance&#8217;s dictionary, never a
class&#8217;s dictionary.  If the class has a <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></tt></a> or
<a class="reference internal" href="#object.__delattr__" title="object.__delattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__delattr__()</span></tt></a> method, this is called instead of updating the instance
dictionary directly.</p>
<p id="index-49">Class instances can pretend to be numbers, sequences, or mappings if they have
methods with certain special names.  See section <a class="reference internal" href="#specialnames"><em>Special method names</em></a>.</p>
<p class="last" id="index-50">Special attributes: <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt></a> is the attribute dictionary;
<a class="reference internal" href="../library/stdtypes.html#instance.__class__" title="instance.__class__"><tt class="xref py py-attr docutils literal"><span class="pre">__class__</span></tt></a> is the instance&#8217;s class.</p>
</dd>
<dt>I/O objects (also known as file objects)</dt>
<dd><p class="first" id="index-51">A <a class="reference internal" href="../glossary.html#term-file-object"><em class="xref std std-term">file object</em></a> represents an open file.  Various shortcuts are
available to create file objects: the <a class="reference internal" href="../library/functions.html#open" title="open"><tt class="xref py py-func docutils literal"><span class="pre">open()</span></tt></a> built-in function, and
also <a class="reference internal" href="../library/os.html#os.popen" title="os.popen"><tt class="xref py py-func docutils literal"><span class="pre">os.popen()</span></tt></a>, <a class="reference internal" href="../library/os.html#os.fdopen" title="os.fdopen"><tt class="xref py py-func docutils literal"><span class="pre">os.fdopen()</span></tt></a>, and the
<a class="reference internal" href="../library/socket.html#socket.socket.makefile" title="socket.socket.makefile"><tt class="xref py py-meth docutils literal"><span class="pre">makefile()</span></tt></a> method of socket objects (and perhaps by
other functions or methods provided by extension modules).</p>
<p class="last">The objects <tt class="docutils literal"><span class="pre">sys.stdin</span></tt>, <tt class="docutils literal"><span class="pre">sys.stdout</span></tt> and <tt class="docutils literal"><span class="pre">sys.stderr</span></tt> are
initialized to file objects corresponding to the interpreter&#8217;s standard
input, output and error streams; they are all open in text mode and
therefore follow the interface defined by the <a class="reference internal" href="../library/io.html#io.TextIOBase" title="io.TextIOBase"><tt class="xref py py-class docutils literal"><span class="pre">io.TextIOBase</span></tt></a>
abstract class.</p>
</dd>
<dt>Internal types</dt>
<dd><p class="first" id="index-52">A few types used internally by the interpreter are exposed to the user. Their
definitions may change with future versions of the interpreter, but they are
mentioned here for completeness.</p>
<dl class="docutils">
<dt>Code objects</dt>
<dd><p class="first" id="index-53">Code objects represent <em>byte-compiled</em> executable Python code, or <a class="reference internal" href="../glossary.html#term-bytecode"><em class="xref std std-term">bytecode</em></a>.
The difference between a code object and a function object is that the function
object contains an explicit reference to the function&#8217;s globals (the module in
which it was defined), while a code object contains no context; also the default
argument values are stored in the function object, not in the code object
(because they represent values calculated at run-time).  Unlike function
objects, code objects are immutable and contain no references (directly or
indirectly) to mutable objects.</p>
<p id="index-54">Special read-only attributes: <tt class="xref py py-attr docutils literal"><span class="pre">co_name</span></tt> gives the function name;
<tt class="xref py py-attr docutils literal"><span class="pre">co_argcount</span></tt> is the number of positional arguments (including arguments
with default values); <tt class="xref py py-attr docutils literal"><span class="pre">co_nlocals</span></tt> is the number of local variables used
by the function (including arguments); <tt class="xref py py-attr docutils literal"><span class="pre">co_varnames</span></tt> is a tuple containing
the names of the local variables (starting with the argument names);
<tt class="xref py py-attr docutils literal"><span class="pre">co_cellvars</span></tt> is a tuple containing the names of local variables that are
referenced by nested functions; <tt class="xref py py-attr docutils literal"><span class="pre">co_freevars</span></tt> is a tuple containing the
names of free variables; <tt class="xref py py-attr docutils literal"><span class="pre">co_code</span></tt> is a string representing the sequence
of bytecode instructions; <tt class="xref py py-attr docutils literal"><span class="pre">co_consts</span></tt> is a tuple containing the literals
used by the bytecode; <tt class="xref py py-attr docutils literal"><span class="pre">co_names</span></tt> is a tuple containing the names used by
the bytecode; <tt class="xref py py-attr docutils literal"><span class="pre">co_filename</span></tt> is the filename from which the code was
compiled; <tt class="xref py py-attr docutils literal"><span class="pre">co_firstlineno</span></tt> is the first line number of the function;
<tt class="xref py py-attr docutils literal"><span class="pre">co_lnotab</span></tt> is a string encoding the mapping from bytecode offsets to
line numbers (for details see the source code of the interpreter);
<tt class="xref py py-attr docutils literal"><span class="pre">co_stacksize</span></tt> is the required stack size (including local variables);
<tt class="xref py py-attr docutils literal"><span class="pre">co_flags</span></tt> is an integer encoding a number of flags for the interpreter.</p>
<p id="index-55">The following flag bits are defined for <tt class="xref py py-attr docutils literal"><span class="pre">co_flags</span></tt>: bit <tt class="docutils literal"><span class="pre">0x04</span></tt> is set if
the function uses the <tt class="docutils literal"><span class="pre">*arguments</span></tt> syntax to accept an arbitrary number of
positional arguments; bit <tt class="docutils literal"><span class="pre">0x08</span></tt> is set if the function uses the
<tt class="docutils literal"><span class="pre">**keywords</span></tt> syntax to accept arbitrary keyword arguments; bit <tt class="docutils literal"><span class="pre">0x20</span></tt> is set
if the function is a generator.</p>
<p>Future feature declarations (<tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></tt>) also use bits
in <tt class="xref py py-attr docutils literal"><span class="pre">co_flags</span></tt> to indicate whether a code object was compiled with a
particular feature enabled: bit <tt class="docutils literal"><span class="pre">0x2000</span></tt> is set if the function was compiled
with future division enabled; bits <tt class="docutils literal"><span class="pre">0x10</span></tt> and <tt class="docutils literal"><span class="pre">0x1000</span></tt> were used in earlier
versions of Python.</p>
<p>Other bits in <tt class="xref py py-attr docutils literal"><span class="pre">co_flags</span></tt> are reserved for internal use.</p>
<p class="last" id="index-56">If a code object represents a function, the first item in <tt class="xref py py-attr docutils literal"><span class="pre">co_consts</span></tt> is
the documentation string of the function, or <tt class="docutils literal"><span class="pre">None</span></tt> if undefined.</p>
</dd>
</dl>
<dl class="last docutils" id="frame-objects">
<dt>Frame objects</dt>
<dd><p class="first" id="index-57">Frame objects represent execution frames.  They may occur in traceback objects
(see below).</p>
<p id="index-58">Special read-only attributes: <tt class="xref py py-attr docutils literal"><span class="pre">f_back</span></tt> is to the previous stack frame
(towards the caller), or <tt class="docutils literal"><span class="pre">None</span></tt> if this is the bottom stack frame;
<tt class="xref py py-attr docutils literal"><span class="pre">f_code</span></tt> is the code object being executed in this frame; <tt class="xref py py-attr docutils literal"><span class="pre">f_locals</span></tt>
is the dictionary used to look up local variables; <tt class="xref py py-attr docutils literal"><span class="pre">f_globals</span></tt> is used for
global variables; <tt class="xref py py-attr docutils literal"><span class="pre">f_builtins</span></tt> is used for built-in (intrinsic) names;
<tt class="xref py py-attr docutils literal"><span class="pre">f_lasti</span></tt> gives the precise instruction (this is an index into the
bytecode string of the code object).</p>
<p id="index-59">Special writable attributes: <tt class="xref py py-attr docutils literal"><span class="pre">f_trace</span></tt>, if not <tt class="docutils literal"><span class="pre">None</span></tt>, is a function
called at the start of each source code line (this is used by the debugger);
<tt class="xref py py-attr docutils literal"><span class="pre">f_lineno</span></tt> is the current line number of the frame &#8212; writing to this
from within a trace function jumps to the given line (only for the bottom-most
frame).  A debugger can implement a Jump command (aka Set Next Statement)
by writing to f_lineno.</p>
<p>Frame objects support one method:</p>
<dl class="last method">
<dt id="frame.clear">
<tt class="descclassname">frame.</tt><tt class="descname">clear</tt><big>(</big><big>)</big><a class="headerlink" href="#frame.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>This method clears all references to local variables held by the
frame.  Also, if the frame belonged to a generator, the generator
is finalized.  This helps break reference cycles involving frame
objects (for example when catching an exception and storing its
traceback for later use).</p>
<p><a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a> is raised if the frame is currently executing.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.4.</span></p>
</div>
</dd></dl>

</dd>
<dt>Traceback objects</dt>
<dd><p class="first" id="index-60">Traceback objects represent a stack trace of an exception.  A traceback object
is created when an exception occurs.  When the search for an exception handler
unwinds the execution stack, at each unwound level a traceback object is
inserted in front of the current traceback.  When an exception handler is
entered, the stack trace is made available to the program. (See section
<a class="reference internal" href="compound_stmts.html#try"><em>The try statement</em></a>.) It is accessible as the third item of the
tuple returned by <tt class="docutils literal"><span class="pre">sys.exc_info()</span></tt>. When the program contains no suitable
handler, the stack trace is written (nicely formatted) to the standard error
stream; if the interpreter is interactive, it is also made available to the user
as <tt class="docutils literal"><span class="pre">sys.last_traceback</span></tt>.</p>
<p class="last" id="index-61">Special read-only attributes: <tt class="xref py py-attr docutils literal"><span class="pre">tb_next</span></tt> is the next level in the stack
trace (towards the frame where the exception occurred), or <tt class="docutils literal"><span class="pre">None</span></tt> if there is
no next level; <tt class="xref py py-attr docutils literal"><span class="pre">tb_frame</span></tt> points to the execution frame of the current
level; <tt class="xref py py-attr docutils literal"><span class="pre">tb_lineno</span></tt> gives the line number where the exception occurred;
<tt class="xref py py-attr docutils literal"><span class="pre">tb_lasti</span></tt> indicates the precise instruction.  The line number and last
instruction in the traceback may differ from the line number of its frame object
if the exception occurred in a <a class="reference internal" href="compound_stmts.html#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a> statement with no matching except
clause or with a finally clause.</p>
</dd>
<dt>Slice objects</dt>
<dd><p class="first" id="index-62">Slice objects are used to represent slices for <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>
methods.  They are also created by the built-in <a class="reference internal" href="../library/functions.html#slice" title="slice"><tt class="xref py py-func docutils literal"><span class="pre">slice()</span></tt></a> function.</p>
<p id="index-63">Special read-only attributes: <tt class="xref py py-attr docutils literal"><span class="pre">start</span></tt> is the lower bound;
<tt class="xref py py-attr docutils literal"><span class="pre">stop</span></tt> is the upper bound; <tt class="xref py py-attr docutils literal"><span class="pre">step</span></tt> is the step
value; each is <tt class="docutils literal"><span class="pre">None</span></tt> if omitted.  These attributes can have any type.</p>
<p>Slice objects support one method:</p>
<dl class="last method">
<dt id="slice.indices">
<tt class="descclassname">slice.</tt><tt class="descname">indices</tt><big>(</big><em>self</em>, <em>length</em><big>)</big><a class="headerlink" href="#slice.indices" title="Permalink to this definition">¶</a></dt>
<dd><p>This method takes a single integer argument <em>length</em> and computes
information about the slice that the slice object would describe if
applied to a sequence of <em>length</em> items.  It returns a tuple of three
integers; respectively these are the <em>start</em> and <em>stop</em> indices and the
<em>step</em> or stride length of the slice. Missing or out-of-bounds indices
are handled in a manner consistent with regular slices.</p>
</dd></dl>

</dd>
<dt>Static method objects</dt>
<dd>Static method objects provide a way of defeating the transformation of function
objects to method objects described above. A static method object is a wrapper
around any other object, usually a user-defined method object. When a static
method object is retrieved from a class or a class instance, the object actually
returned is the wrapped object, which is not subject to any further
transformation. Static method objects are not themselves callable, although the
objects they wrap usually are. Static method objects are created by the built-in
<a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><tt class="xref py py-func docutils literal"><span class="pre">staticmethod()</span></tt></a> constructor.</dd>
<dt>Class method objects</dt>
<dd>A class method object, like a static method object, is a wrapper around another
object that alters the way in which that object is retrieved from classes and
class instances. The behaviour of class method objects upon such retrieval is
described above, under &#8220;User-defined methods&#8221;. Class method objects are created
by the built-in <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><tt class="xref py py-func docutils literal"><span class="pre">classmethod()</span></tt></a> constructor.</dd>
</dl>
</dd>
</dl>
</div>
<div class="section" id="special-method-names">
<span id="specialnames"></span><h2>3.3. Special method names<a class="headerlink" href="#special-method-names" title="Permalink to this headline">¶</a></h2>
<p id="index-64">A class can implement certain operations that are invoked by special syntax
(such as arithmetic operations or subscripting and slicing) by defining methods
with special names. This is Python&#8217;s approach to <em class="dfn">operator overloading</em>,
allowing classes to define their own behavior with respect to language
operators.  For instance, if a class defines a method named <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>,
and <tt class="docutils literal"><span class="pre">x</span></tt> is an instance of this class, then <tt class="docutils literal"><span class="pre">x[i]</span></tt> is roughly equivalent
to <tt class="docutils literal"><span class="pre">type(x).__getitem__(x,</span> <span class="pre">i)</span></tt>.  Except where mentioned, attempts to execute an
operation raise an exception when no appropriate method is defined (typically
<a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a> or <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a>).</p>
<p>When implementing a class that emulates any built-in type, it is important that
the emulation only be implemented to the degree that it makes sense for the
object being modelled.  For example, some sequences may work well with retrieval
of individual elements, but extracting a slice may not make sense.  (One example
of this is the <tt class="xref py py-class docutils literal"><span class="pre">NodeList</span></tt> interface in the W3C&#8217;s Document
Object Model.)</p>
<div class="section" id="basic-customization">
<span id="customization"></span><h3>3.3.1. Basic customization<a class="headerlink" href="#basic-customization" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="object.__new__">
<tt class="descclassname">object.</tt><tt class="descname">__new__</tt><big>(</big><em>cls</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#object.__new__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-65">Called to create a new instance of class <em>cls</em>.  <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> is a static
method (special-cased so you need not declare it as such) that takes the class
of which an instance was requested as its first argument.  The remaining
arguments are those passed to the object constructor expression (the call to the
class).  The return value of <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> should be the new object instance
(usually an instance of <em>cls</em>).</p>
<p>Typical implementations create a new instance of the class by invoking the
superclass&#8217;s <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> method using <tt class="docutils literal"><span class="pre">super(currentclass,</span>
<span class="pre">cls).__new__(cls[,</span> <span class="pre">...])</span></tt> with appropriate arguments and then modifying the
newly-created instance as necessary before returning it.</p>
<p>If <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> returns an instance of <em>cls</em>, then the new instance&#8217;s
<a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method will be invoked like <tt class="docutils literal"><span class="pre">__init__(self[,</span> <span class="pre">...])</span></tt>, where
<em>self</em> is the new instance and the remaining arguments are the same as were
passed to <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a>.</p>
<p>If <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> does not return an instance of <em>cls</em>, then the new instance&#8217;s
<a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method will not be invoked.</p>
<p><a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> is intended mainly to allow subclasses of immutable types (like
int, str, or tuple) to customize instance creation.  It is also commonly
overridden in custom metaclasses in order to customize class creation.</p>
</dd></dl>

<dl class="method">
<dt id="object.__init__">
<tt class="descclassname">object.</tt><tt class="descname">__init__</tt><big>(</big><em>self</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#object.__init__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-66">Called after the instance has been created (by <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a>), but before
it is returned to the caller.  The arguments are those passed to the
class constructor expression.  If a base class has an <a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a>
method, the derived class&#8217;s <a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> method, if any, must explicitly
call it to ensure proper initialization of the base class part of the
instance; for example: <tt class="docutils literal"><span class="pre">BaseClass.__init__(self,</span> <span class="pre">[args...])</span></tt>.</p>
<p>Because <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> and <a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> work together in constructing
objects (<a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> to create it, and <a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a> to customise it),
no non-<tt class="docutils literal"><span class="pre">None</span></tt> value may be returned by <a class="reference internal" href="#object.__init__" title="object.__init__"><tt class="xref py py-meth docutils literal"><span class="pre">__init__()</span></tt></a>; doing so will
cause a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> to be raised at runtime.</p>
</dd></dl>

<dl class="method">
<dt id="object.__del__">
<tt class="descclassname">object.</tt><tt class="descname">__del__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__del__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-67">Called when the instance is about to be destroyed.  This is also called a
destructor.  If a base class has a <a class="reference internal" href="#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> method, the derived class&#8217;s
<a class="reference internal" href="#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> method, if any, must explicitly call it to ensure proper
deletion of the base class part of the instance.  Note that it is possible
(though not recommended!) for the <a class="reference internal" href="#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> method to postpone destruction
of the instance by creating a new reference to it.  It may then be called at a
later time when this new reference is deleted.  It is not guaranteed that
<a class="reference internal" href="#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> methods are called for objects that still exist when the
interpreter exits.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><tt class="docutils literal"><span class="pre">del</span> <span class="pre">x</span></tt> doesn&#8217;t directly call <tt class="docutils literal"><span class="pre">x.__del__()</span></tt> &#8212; the former decrements
the reference count for <tt class="docutils literal"><span class="pre">x</span></tt> by one, and the latter is only called when
<tt class="docutils literal"><span class="pre">x</span></tt>&#8216;s reference count reaches zero.  Some common situations that may
prevent the reference count of an object from going to zero include:
circular references between objects (e.g., a doubly-linked list or a tree
data structure with parent and child pointers); a reference to the object
on the stack frame of a function that caught an exception (the traceback
stored in <tt class="docutils literal"><span class="pre">sys.exc_info()[2]</span></tt> keeps the stack frame alive); or a
reference to the object on the stack frame that raised an unhandled
exception in interactive mode (the traceback stored in
<tt class="docutils literal"><span class="pre">sys.last_traceback</span></tt> keeps the stack frame alive).  The first situation
can only be remedied by explicitly breaking the cycles; the second can be
resolved by freeing the reference to the traceback object when it is no
longer useful, and the third can be resolved by storing <tt class="docutils literal"><span class="pre">None</span></tt> in
<tt class="docutils literal"><span class="pre">sys.last_traceback</span></tt>.
Circular references which are garbage are detected and cleaned up when
the cyclic garbage collector is enabled (it&#8217;s on by default). Refer to the
documentation for the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><tt class="xref py py-mod docutils literal"><span class="pre">gc</span></tt></a> module for more information about this
topic.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Due to the precarious circumstances under which <a class="reference internal" href="#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> methods are
invoked, exceptions that occur during their execution are ignored, and a warning
is printed to <tt class="docutils literal"><span class="pre">sys.stderr</span></tt> instead.  Also, when <a class="reference internal" href="#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> is invoked in
response to a module being deleted (e.g., when execution of the program is
done), other globals referenced by the <a class="reference internal" href="#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> method may already have
been deleted or in the process of being torn down (e.g. the import
machinery shutting down).  For this reason, <a class="reference internal" href="#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> methods
should do the absolute
minimum needed to maintain external invariants.  Starting with version 1.5,
Python guarantees that globals whose name begins with a single underscore are
deleted from their module before other globals are deleted; if no other
references to such globals exist, this may help in assuring that imported
modules are still available at the time when the <a class="reference internal" href="#object.__del__" title="object.__del__"><tt class="xref py py-meth docutils literal"><span class="pre">__del__()</span></tt></a> method is
called.</p>
<span class="target" id="index-68"></span></div>
</dd></dl>

<dl class="method">
<dt id="object.__repr__">
<tt class="descclassname">object.</tt><tt class="descname">__repr__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__repr__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called by the <a class="reference internal" href="../library/functions.html#repr" title="repr"><tt class="xref py py-func docutils literal"><span class="pre">repr()</span></tt></a> built-in function to compute the &#8220;official&#8221; string
representation of an object.  If at all possible, this should look like a
valid Python expression that could be used to recreate an object with the
same value (given an appropriate environment).  If this is not possible, a
string of the form <tt class="docutils literal"><span class="pre">&lt;...some</span> <span class="pre">useful</span> <span class="pre">description...&gt;</span></tt> should be returned.
The return value must be a string object. If a class defines <a class="reference internal" href="#object.__repr__" title="object.__repr__"><tt class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></tt></a>
but not <a class="reference internal" href="#object.__str__" title="object.__str__"><tt class="xref py py-meth docutils literal"><span class="pre">__str__()</span></tt></a>, then <a class="reference internal" href="#object.__repr__" title="object.__repr__"><tt class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></tt></a> is also used when an
&#8220;informal&#8221; string representation of instances of that class is required.</p>
<p>This is typically used for debugging, so it is important that the representation
is information-rich and unambiguous.</p>
<span class="target" id="index-69"></span></dd></dl>

<dl class="method">
<dt id="object.__str__">
<tt class="descclassname">object.</tt><tt class="descname">__str__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__str__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called by <a class="reference internal" href="../library/stdtypes.html#str" title="str"><tt class="xref py py-func docutils literal"><span class="pre">str(object)</span></tt></a> and the built-in functions
<a class="reference internal" href="../library/functions.html#format" title="format"><tt class="xref py py-func docutils literal"><span class="pre">format()</span></tt></a> and <a class="reference internal" href="../library/functions.html#print" title="print"><tt class="xref py py-func docutils literal"><span class="pre">print()</span></tt></a> to compute the &#8220;informal&#8221; or nicely
printable string representation of an object.  The return value must be a
<a class="reference internal" href="../library/stdtypes.html#textseq"><em>string</em></a> object.</p>
<p>This method differs from <a class="reference internal" href="#object.__repr__" title="object.__repr__"><tt class="xref py py-meth docutils literal"><span class="pre">object.__repr__()</span></tt></a> in that there is no
expectation that <a class="reference internal" href="#object.__str__" title="object.__str__"><tt class="xref py py-meth docutils literal"><span class="pre">__str__()</span></tt></a> return a valid Python expression: a more
convenient or concise representation can be used.</p>
<p>The default implementation defined by the built-in type <a class="reference internal" href="../library/functions.html#object" title="object"><tt class="xref py py-class docutils literal"><span class="pre">object</span></tt></a>
calls <a class="reference internal" href="#object.__repr__" title="object.__repr__"><tt class="xref py py-meth docutils literal"><span class="pre">object.__repr__()</span></tt></a>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__bytes__">
<tt class="descclassname">object.</tt><tt class="descname">__bytes__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__bytes__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-70">Called by <a class="reference internal" href="../library/functions.html#bytes" title="bytes"><tt class="xref py py-func docutils literal"><span class="pre">bytes()</span></tt></a> to compute a byte-string representation of an
object. This should return a <tt class="docutils literal"><span class="pre">bytes</span></tt> object.</p>
<span class="target" id="index-71"></span></dd></dl>

<dl class="method">
<dt id="object.__format__">
<tt class="descclassname">object.</tt><tt class="descname">__format__</tt><big>(</big><em>self</em>, <em>format_spec</em><big>)</big><a class="headerlink" href="#object.__format__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called by the <a class="reference internal" href="../library/functions.html#format" title="format"><tt class="xref py py-func docutils literal"><span class="pre">format()</span></tt></a> built-in function (and by extension, the
<a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><tt class="xref py py-meth docutils literal"><span class="pre">str.format()</span></tt></a> method of class <a class="reference internal" href="../library/stdtypes.html#str" title="str"><tt class="xref py py-class docutils literal"><span class="pre">str</span></tt></a>) to produce a &#8220;formatted&#8221;
string representation of an object. The <tt class="docutils literal"><span class="pre">format_spec</span></tt> argument is
a string that contains a description of the formatting options desired.
The interpretation of the <tt class="docutils literal"><span class="pre">format_spec</span></tt> argument is up to the type
implementing <a class="reference internal" href="#object.__format__" title="object.__format__"><tt class="xref py py-meth docutils literal"><span class="pre">__format__()</span></tt></a>, however most classes will either
delegate formatting to one of the built-in types, or use a similar
formatting option syntax.</p>
<p>See <a class="reference internal" href="../library/string.html#formatspec"><em>Format Specification Mini-Language</em></a> for a description of the standard formatting syntax.</p>
<p>The return value must be a string object.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.4: </span>The __format__ method of <tt class="docutils literal"><span class="pre">object</span></tt> itself raises a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a>
if passed any non-empty string.</p>
</div>
</dd></dl>

<span class="target" id="richcmpfuncs"></span><dl class="method">
<dt id="object.__lt__">
<tt class="descclassname">object.</tt><tt class="descname">__lt__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__lt__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__le__">
<tt class="descclassname">object.</tt><tt class="descname">__le__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__le__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__eq__">
<tt class="descclassname">object.</tt><tt class="descname">__eq__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__eq__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ne__">
<tt class="descclassname">object.</tt><tt class="descname">__ne__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__ne__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__gt__">
<tt class="descclassname">object.</tt><tt class="descname">__gt__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__gt__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ge__">
<tt class="descclassname">object.</tt><tt class="descname">__ge__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__ge__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-72">These are the so-called &#8220;rich comparison&#8221; methods. The correspondence between
operator symbols and method names is as follows: <tt class="docutils literal"><span class="pre">x&lt;y</span></tt> calls <tt class="docutils literal"><span class="pre">x.__lt__(y)</span></tt>,
<tt class="docutils literal"><span class="pre">x&lt;=y</span></tt> calls <tt class="docutils literal"><span class="pre">x.__le__(y)</span></tt>, <tt class="docutils literal"><span class="pre">x==y</span></tt> calls <tt class="docutils literal"><span class="pre">x.__eq__(y)</span></tt>, <tt class="docutils literal"><span class="pre">x!=y</span></tt> calls
<tt class="docutils literal"><span class="pre">x.__ne__(y)</span></tt>, <tt class="docutils literal"><span class="pre">x&gt;y</span></tt> calls <tt class="docutils literal"><span class="pre">x.__gt__(y)</span></tt>, and <tt class="docutils literal"><span class="pre">x&gt;=y</span></tt> calls
<tt class="docutils literal"><span class="pre">x.__ge__(y)</span></tt>.</p>
<p>A rich comparison method may return the singleton <tt class="docutils literal"><span class="pre">NotImplemented</span></tt> if it does
not implement the operation for a given pair of arguments. By convention,
<tt class="docutils literal"><span class="pre">False</span></tt> and <tt class="docutils literal"><span class="pre">True</span></tt> are returned for a successful comparison. However, these
methods can return any value, so if the comparison operator is used in a Boolean
context (e.g., in the condition of an <tt class="docutils literal"><span class="pre">if</span></tt> statement), Python will call
<a class="reference internal" href="../library/functions.html#bool" title="bool"><tt class="xref py py-func docutils literal"><span class="pre">bool()</span></tt></a> on the value to determine if the result is true or false.</p>
<p>By default, <a class="reference internal" href="#object.__ne__" title="object.__ne__"><tt class="xref py py-meth docutils literal"><span class="pre">__ne__()</span></tt></a> delegates to <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> and
inverts the result unless it is <tt class="docutils literal"><span class="pre">NotImplemented</span></tt>.  There are no other
implied relationships among the comparison operators, for example,
the truth of <tt class="docutils literal"><span class="pre">(x&lt;y</span> <span class="pre">or</span> <span class="pre">x==y)</span></tt> does not imply <tt class="docutils literal"><span class="pre">x&lt;=y</span></tt>.
To automatically generate ordering operations from a single root operation,
see <a class="reference internal" href="../library/functools.html#functools.total_ordering" title="functools.total_ordering"><tt class="xref py py-func docutils literal"><span class="pre">functools.total_ordering()</span></tt></a>.</p>
<p>See the paragraph on <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> for
some important notes on creating <a class="reference internal" href="../glossary.html#term-hashable"><em class="xref std std-term">hashable</em></a> objects which support
custom comparison operations and are usable as dictionary keys.</p>
<p>There are no swapped-argument versions of these methods (to be used when the
left argument does not support the operation but the right argument does);
rather, <a class="reference internal" href="#object.__lt__" title="object.__lt__"><tt class="xref py py-meth docutils literal"><span class="pre">__lt__()</span></tt></a> and <a class="reference internal" href="#object.__gt__" title="object.__gt__"><tt class="xref py py-meth docutils literal"><span class="pre">__gt__()</span></tt></a> are each other&#8217;s reflection,
<a class="reference internal" href="#object.__le__" title="object.__le__"><tt class="xref py py-meth docutils literal"><span class="pre">__le__()</span></tt></a> and <a class="reference internal" href="#object.__ge__" title="object.__ge__"><tt class="xref py py-meth docutils literal"><span class="pre">__ge__()</span></tt></a> are each other&#8217;s reflection, and
<a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> and <a class="reference internal" href="#object.__ne__" title="object.__ne__"><tt class="xref py py-meth docutils literal"><span class="pre">__ne__()</span></tt></a> are their own reflection.
If the operands are of different types, and right operand&#8217;s type is
a direct or indirect subclass of the left operand&#8217;s type,
the reflected method of the right operand has priority, otherwise
the left operand&#8217;s method has priority.  Virtual subclassing is
not considered.</p>
</dd></dl>

<dl class="method">
<dt id="object.__hash__">
<tt class="descclassname">object.</tt><tt class="descname">__hash__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__hash__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-73">Called by built-in function <a class="reference internal" href="../library/functions.html#hash" title="hash"><tt class="xref py py-func docutils literal"><span class="pre">hash()</span></tt></a> and for operations on members of
hashed collections including <a class="reference internal" href="../library/stdtypes.html#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a>, <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a>, and
<a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a>.  <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> should return an integer.  The only
required property is that objects which compare equal have the same hash
value; it is advised to somehow mix together (e.g. using exclusive or) the
hash values for the components of the object that also play a part in
comparison of objects.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="../library/functions.html#hash" title="hash"><tt class="xref py py-func docutils literal"><span class="pre">hash()</span></tt></a> truncates the value returned from an object&#8217;s custom
<a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> method to the size of a <tt class="xref c c-type docutils literal"><span class="pre">Py_ssize_t</span></tt>.  This is
typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds.  If an
object&#8217;s   <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> must interoperate on builds of different bit
sizes, be sure to check the width on all supported builds.  An easy way
to do this is with
<tt class="docutils literal"><span class="pre">python</span> <span class="pre">-c</span> <span class="pre">&quot;import</span> <span class="pre">sys;</span> <span class="pre">print(sys.hash_info.width)&quot;</span></tt></p>
</div>
<p>If a class does not define an <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> method it should not define a
<a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> operation either; if it defines <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> but not
<a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a>, its instances will not be usable as items in hashable
collections.  If a class defines mutable objects and implements an
<a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> method, it should not implement <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a>, since the
implementation of hashable collections requires that a key&#8217;s hash value is
immutable (if the object&#8217;s hash value changes, it will be in the wrong hash
bucket).</p>
<p>User-defined classes have <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> and <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> methods
by default; with them, all objects compare unequal (except with themselves)
and <tt class="docutils literal"><span class="pre">x.__hash__()</span></tt> returns an appropriate value such that <tt class="docutils literal"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></tt>
implies both that <tt class="docutils literal"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">y</span></tt> and <tt class="docutils literal"><span class="pre">hash(x)</span> <span class="pre">==</span> <span class="pre">hash(y)</span></tt>.</p>
<p>A class that overrides <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> and does not define <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a>
will have its <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> implicitly set to <tt class="docutils literal"><span class="pre">None</span></tt>.  When the
<a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> method of a class is <tt class="docutils literal"><span class="pre">None</span></tt>, instances of the class will
raise an appropriate <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> when a program attempts to retrieve
their hash value, and will also be correctly identified as unhashable when
checking <tt class="docutils literal"><span class="pre">isinstance(obj,</span> <span class="pre">collections.Hashable</span></tt>).</p>
<p>If a class that overrides <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> needs to retain the implementation
of <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> from a parent class, the interpreter must be told this
explicitly by setting <tt class="docutils literal"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">&lt;ParentClass&gt;.__hash__</span></tt>.</p>
<p>If a class that does not override <a class="reference internal" href="#object.__eq__" title="object.__eq__"><tt class="xref py py-meth docutils literal"><span class="pre">__eq__()</span></tt></a> wishes to suppress hash
support, it should include <tt class="docutils literal"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></tt> in the class definition.
A class which defines its own <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> that explicitly raises
a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> would be incorrectly identified as hashable by
an <tt class="docutils literal"><span class="pre">isinstance(obj,</span> <span class="pre">collections.Hashable)</span></tt> call.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>By default, the <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> values of str, bytes and datetime
objects are &#8220;salted&#8221; with an unpredictable random value.  Although they
remain constant within an individual Python process, they are not
predictable between repeated invocations of Python.</p>
<p>This is intended to provide protection against a denial-of-service caused
by carefully-chosen inputs that exploit the worst case performance of a
dict insertion, O(n^2) complexity.  See
<a class="reference external" href="http://www.ocert.org/advisories/ocert-2011-003.html">http://www.ocert.org/advisories/ocert-2011-003.html</a> for details.</p>
<p>Changing hash values affects the iteration order of dicts, sets and
other mappings.  Python has never made guarantees about this ordering
(and it typically varies between 32-bit and 64-bit builds).</p>
<p class="last">See also <span class="target" id="index-74"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONHASHSEED"><tt class="xref std std-envvar docutils literal"><span class="pre">PYTHONHASHSEED</span></tt></a>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.3: </span>Hash randomization is enabled by default.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__bool__">
<tt class="descclassname">object.</tt><tt class="descname">__bool__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__bool__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-75">Called to implement truth value testing and the built-in operation
<tt class="docutils literal"><span class="pre">bool()</span></tt>; should return <tt class="docutils literal"><span class="pre">False</span></tt> or <tt class="docutils literal"><span class="pre">True</span></tt>.  When this method is not
defined, <a class="reference internal" href="#object.__len__" title="object.__len__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></a> is called, if it is defined, and the object is
considered true if its result is nonzero.  If a class defines neither
<a class="reference internal" href="#object.__len__" title="object.__len__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></a> nor <a class="reference internal" href="#object.__bool__" title="object.__bool__"><tt class="xref py py-meth docutils literal"><span class="pre">__bool__()</span></tt></a>, all its instances are considered
true.</p>
</dd></dl>

</div>
<div class="section" id="customizing-attribute-access">
<span id="attribute-access"></span><h3>3.3.2. Customizing attribute access<a class="headerlink" href="#customizing-attribute-access" title="Permalink to this headline">¶</a></h3>
<p>The following methods can be defined to customize the meaning of attribute
access (use of, assignment to, or deletion of <tt class="docutils literal"><span class="pre">x.name</span></tt>) for class instances.</p>
<dl class="method">
<dt id="object.__getattr__">
<tt class="descclassname">object.</tt><tt class="descname">__getattr__</tt><big>(</big><em>self</em>, <em>name</em><big>)</big><a class="headerlink" href="#object.__getattr__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when an attribute lookup has not found the attribute in the usual places
(i.e. it is not an instance attribute nor is it found in the class tree for
<tt class="docutils literal"><span class="pre">self</span></tt>).  <tt class="docutils literal"><span class="pre">name</span></tt> is the attribute name. This method should return the
(computed) attribute value or raise an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a> exception.</p>
<p>Note that if the attribute is found through the normal mechanism,
<a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></tt></a> is not called.  (This is an intentional asymmetry between
<a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></tt></a> and <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></tt></a>.) This is done both for efficiency
reasons and because otherwise <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></tt></a> would have no way to access
other attributes of the instance.  Note that at least for instance variables,
you can fake total control by not inserting any values in the instance attribute
dictionary (but instead inserting them in another object).  See the
<a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></tt></a> method below for a way to actually get total control
over attribute access.</p>
</dd></dl>

<dl class="method">
<dt id="object.__getattribute__">
<tt class="descclassname">object.</tt><tt class="descname">__getattribute__</tt><big>(</big><em>self</em>, <em>name</em><big>)</big><a class="headerlink" href="#object.__getattribute__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called unconditionally to implement attribute accesses for instances of the
class. If the class also defines <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></tt></a>, the latter will not be
called unless <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></tt></a> either calls it explicitly or raises an
<a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a>. This method should return the (computed) attribute value
or raise an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a> exception. In order to avoid infinite
recursion in this method, its implementation should always call the base class
method with the same name to access any attributes it needs, for example,
<tt class="docutils literal"><span class="pre">object.__getattribute__(self,</span> <span class="pre">name)</span></tt>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This method may still be bypassed when looking up special methods as the
result of implicit invocation via language syntax or built-in functions.
See <a class="reference internal" href="#special-lookup"><em>Special method lookup</em></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__setattr__">
<tt class="descclassname">object.</tt><tt class="descname">__setattr__</tt><big>(</big><em>self</em>, <em>name</em>, <em>value</em><big>)</big><a class="headerlink" href="#object.__setattr__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when an attribute assignment is attempted.  This is called instead of
the normal mechanism (i.e. store the value in the instance dictionary).
<em>name</em> is the attribute name, <em>value</em> is the value to be assigned to it.</p>
<p>If <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></tt></a> wants to assign to an instance attribute, it should
call the base class method with the same name, for example,
<tt class="docutils literal"><span class="pre">object.__setattr__(self,</span> <span class="pre">name,</span> <span class="pre">value)</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__delattr__">
<tt class="descclassname">object.</tt><tt class="descname">__delattr__</tt><big>(</big><em>self</em>, <em>name</em><big>)</big><a class="headerlink" href="#object.__delattr__" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__setattr__()</span></tt></a> but for attribute deletion instead of assignment.  This
should only be implemented if <tt class="docutils literal"><span class="pre">del</span> <span class="pre">obj.name</span></tt> is meaningful for the object.</p>
</dd></dl>

<dl class="method">
<dt id="object.__dir__">
<tt class="descclassname">object.</tt><tt class="descname">__dir__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__dir__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when <a class="reference internal" href="../library/functions.html#dir" title="dir"><tt class="xref py py-func docutils literal"><span class="pre">dir()</span></tt></a> is called on the object. A sequence must be
returned. <a class="reference internal" href="../library/functions.html#dir" title="dir"><tt class="xref py py-func docutils literal"><span class="pre">dir()</span></tt></a> converts the returned sequence to a list and sorts it.</p>
</dd></dl>

<div class="section" id="implementing-descriptors">
<span id="descriptors"></span><h4>3.3.2.1. Implementing Descriptors<a class="headerlink" href="#implementing-descriptors" title="Permalink to this headline">¶</a></h4>
<p>The following methods only apply when an instance of the class containing the
method (a so-called <em>descriptor</em> class) appears in an <em>owner</em> class (the
descriptor must be in either the owner&#8217;s class dictionary or in the class
dictionary for one of its parents).  In the examples below, &#8220;the attribute&#8221;
refers to the attribute whose name is the key of the property in the owner
class&#8217; <tt class="xref py py-attr docutils literal"><span class="pre">__dict__</span></tt>.</p>
<dl class="method">
<dt id="object.__get__">
<tt class="descclassname">object.</tt><tt class="descname">__get__</tt><big>(</big><em>self</em>, <em>instance</em>, <em>owner</em><big>)</big><a class="headerlink" href="#object.__get__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to get the attribute of the owner class (class attribute access) or of an
instance of that class (instance attribute access). <em>owner</em> is always the owner
class, while <em>instance</em> is the instance that the attribute was accessed through,
or <tt class="docutils literal"><span class="pre">None</span></tt> when the attribute is accessed through the <em>owner</em>.  This method
should return the (computed) attribute value or raise an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a>
exception.</p>
</dd></dl>

<dl class="method">
<dt id="object.__set__">
<tt class="descclassname">object.</tt><tt class="descname">__set__</tt><big>(</big><em>self</em>, <em>instance</em>, <em>value</em><big>)</big><a class="headerlink" href="#object.__set__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to set the attribute on an instance <em>instance</em> of the owner class to a
new value, <em>value</em>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__delete__">
<tt class="descclassname">object.</tt><tt class="descname">__delete__</tt><big>(</big><em>self</em>, <em>instance</em><big>)</big><a class="headerlink" href="#object.__delete__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to delete the attribute on an instance <em>instance</em> of the owner class.</p>
</dd></dl>

<p>The attribute <tt class="xref py py-attr docutils literal"><span class="pre">__objclass__</span></tt> is interpreted by the <a class="reference internal" href="../library/inspect.html#module-inspect" title="inspect: Extract information and source code from live objects."><tt class="xref py py-mod docutils literal"><span class="pre">inspect</span></tt></a> module
as specifying the class where this object was defined (setting this
appropriately can assist in runtime introspection of dynamic class attributes).
For callables, it may indicate that an instance of the given type (or a
subclass) is expected or required as the first positional argument (for example,
CPython sets this attribute for unbound methods that are implemented in C).</p>
</div>
<div class="section" id="invoking-descriptors">
<span id="descriptor-invocation"></span><h4>3.3.2.2. Invoking Descriptors<a class="headerlink" href="#invoking-descriptors" title="Permalink to this headline">¶</a></h4>
<p>In general, a descriptor is an object attribute with &#8220;binding behavior&#8221;, one
whose attribute access has been overridden by methods in the descriptor
protocol:  <a class="reference internal" href="#object.__get__" title="object.__get__"><tt class="xref py py-meth docutils literal"><span class="pre">__get__()</span></tt></a>, <a class="reference internal" href="#object.__set__" title="object.__set__"><tt class="xref py py-meth docutils literal"><span class="pre">__set__()</span></tt></a>, and <a class="reference internal" href="#object.__delete__" title="object.__delete__"><tt class="xref py py-meth docutils literal"><span class="pre">__delete__()</span></tt></a>. If any of
those methods are defined for an object, it is said to be a descriptor.</p>
<p>The default behavior for attribute access is to get, set, or delete the
attribute from an object&#8217;s dictionary. For instance, <tt class="docutils literal"><span class="pre">a.x</span></tt> has a lookup chain
starting with <tt class="docutils literal"><span class="pre">a.__dict__['x']</span></tt>, then <tt class="docutils literal"><span class="pre">type(a).__dict__['x']</span></tt>, and
continuing through the base classes of <tt class="docutils literal"><span class="pre">type(a)</span></tt> excluding metaclasses.</p>
<p>However, if the looked-up value is an object defining one of the descriptor
methods, then Python may override the default behavior and invoke the descriptor
method instead.  Where this occurs in the precedence chain depends on which
descriptor methods were defined and how they were called.</p>
<p>The starting point for descriptor invocation is a binding, <tt class="docutils literal"><span class="pre">a.x</span></tt>. How the
arguments are assembled depends on <tt class="docutils literal"><span class="pre">a</span></tt>:</p>
<dl class="docutils">
<dt>Direct Call</dt>
<dd>The simplest and least common call is when user code directly invokes a
descriptor method:    <tt class="docutils literal"><span class="pre">x.__get__(a)</span></tt>.</dd>
<dt>Instance Binding</dt>
<dd>If binding to an object instance, <tt class="docutils literal"><span class="pre">a.x</span></tt> is transformed into the call:
<tt class="docutils literal"><span class="pre">type(a).__dict__['x'].__get__(a,</span> <span class="pre">type(a))</span></tt>.</dd>
<dt>Class Binding</dt>
<dd>If binding to a class, <tt class="docutils literal"><span class="pre">A.x</span></tt> is transformed into the call:
<tt class="docutils literal"><span class="pre">A.__dict__['x'].__get__(None,</span> <span class="pre">A)</span></tt>.</dd>
<dt>Super Binding</dt>
<dd>If <tt class="docutils literal"><span class="pre">a</span></tt> is an instance of <a class="reference internal" href="../library/functions.html#super" title="super"><tt class="xref py py-class docutils literal"><span class="pre">super</span></tt></a>, then the binding <tt class="docutils literal"><span class="pre">super(B,</span>
<span class="pre">obj).m()</span></tt> searches <tt class="docutils literal"><span class="pre">obj.__class__.__mro__</span></tt> for the base class <tt class="docutils literal"><span class="pre">A</span></tt>
immediately preceding <tt class="docutils literal"><span class="pre">B</span></tt> and then invokes the descriptor with the call:
<tt class="docutils literal"><span class="pre">A.__dict__['m'].__get__(obj,</span> <span class="pre">obj.__class__)</span></tt>.</dd>
</dl>
<p>For instance bindings, the precedence of descriptor invocation depends on the
which descriptor methods are defined.  A descriptor can define any combination
of <a class="reference internal" href="#object.__get__" title="object.__get__"><tt class="xref py py-meth docutils literal"><span class="pre">__get__()</span></tt></a>, <a class="reference internal" href="#object.__set__" title="object.__set__"><tt class="xref py py-meth docutils literal"><span class="pre">__set__()</span></tt></a> and <a class="reference internal" href="#object.__delete__" title="object.__delete__"><tt class="xref py py-meth docutils literal"><span class="pre">__delete__()</span></tt></a>.  If it does not
define <a class="reference internal" href="#object.__get__" title="object.__get__"><tt class="xref py py-meth docutils literal"><span class="pre">__get__()</span></tt></a>, then accessing the attribute will return the descriptor
object itself unless there is a value in the object&#8217;s instance dictionary.  If
the descriptor defines <a class="reference internal" href="#object.__set__" title="object.__set__"><tt class="xref py py-meth docutils literal"><span class="pre">__set__()</span></tt></a> and/or <a class="reference internal" href="#object.__delete__" title="object.__delete__"><tt class="xref py py-meth docutils literal"><span class="pre">__delete__()</span></tt></a>, it is a data
descriptor; if it defines neither, it is a non-data descriptor.  Normally, data
descriptors define both <a class="reference internal" href="#object.__get__" title="object.__get__"><tt class="xref py py-meth docutils literal"><span class="pre">__get__()</span></tt></a> and <a class="reference internal" href="#object.__set__" title="object.__set__"><tt class="xref py py-meth docutils literal"><span class="pre">__set__()</span></tt></a>, while non-data
descriptors have just the <a class="reference internal" href="#object.__get__" title="object.__get__"><tt class="xref py py-meth docutils literal"><span class="pre">__get__()</span></tt></a> method.  Data descriptors with
<a class="reference internal" href="#object.__set__" title="object.__set__"><tt class="xref py py-meth docutils literal"><span class="pre">__set__()</span></tt></a> and <a class="reference internal" href="#object.__get__" title="object.__get__"><tt class="xref py py-meth docutils literal"><span class="pre">__get__()</span></tt></a> defined always override a redefinition in an
instance dictionary.  In contrast, non-data descriptors can be overridden by
instances.</p>
<p>Python methods (including <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><tt class="xref py py-func docutils literal"><span class="pre">staticmethod()</span></tt></a> and <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><tt class="xref py py-func docutils literal"><span class="pre">classmethod()</span></tt></a>) are
implemented as non-data descriptors.  Accordingly, instances can redefine and
override methods.  This allows individual instances to acquire behaviors that
differ from other instances of the same class.</p>
<p>The <a class="reference internal" href="../library/functions.html#property" title="property"><tt class="xref py py-func docutils literal"><span class="pre">property()</span></tt></a> function is implemented as a data descriptor. Accordingly,
instances cannot override the behavior of a property.</p>
</div>
<div class="section" id="slots">
<span id="id2"></span><h4>3.3.2.3. __slots__<a class="headerlink" href="#slots" title="Permalink to this headline">¶</a></h4>
<p>By default, instances of classes have a dictionary for attribute storage.  This
wastes space for objects having very few instance variables.  The space
consumption can become acute when creating large numbers of instances.</p>
<p>The default can be overridden by defining <em>__slots__</em> in a class definition.
The <em>__slots__</em> declaration takes a sequence of instance variables and reserves
just enough space in each instance to hold a value for each variable.  Space is
saved because <em>__dict__</em> is not created for each instance.</p>
<dl class="data">
<dt id="object.__slots__">
<tt class="descclassname">object.</tt><tt class="descname">__slots__</tt><a class="headerlink" href="#object.__slots__" title="Permalink to this definition">¶</a></dt>
<dd><p>This class variable can be assigned a string, iterable, or sequence of
strings with variable names used by instances.  <em>__slots__</em> reserves space
for the declared variables and prevents the automatic creation of <em>__dict__</em>
and <em>__weakref__</em> for each instance.</p>
</dd></dl>

<div class="section" id="notes-on-using-slots">
<h5>3.3.2.3.1. Notes on using <em>__slots__</em><a class="headerlink" href="#notes-on-using-slots" title="Permalink to this headline">¶</a></h5>
<ul class="simple">
<li>When inheriting from a class without <em>__slots__</em>, the <em>__dict__</em> attribute of
that class will always be accessible, so a <em>__slots__</em> definition in the
subclass is meaningless.</li>
<li>Without a <em>__dict__</em> variable, instances cannot be assigned new variables not
listed in the <em>__slots__</em> definition.  Attempts to assign to an unlisted
variable name raises <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a>. If dynamic assignment of new
variables is desired, then add <tt class="docutils literal"><span class="pre">'__dict__'</span></tt> to the sequence of strings in
the <em>__slots__</em> declaration.</li>
<li>Without a <em>__weakref__</em> variable for each instance, classes defining
<em>__slots__</em> do not support weak references to its instances. If weak reference
support is needed, then add <tt class="docutils literal"><span class="pre">'__weakref__'</span></tt> to the sequence of strings in the
<em>__slots__</em> declaration.</li>
<li><em>__slots__</em> are implemented at the class level by creating descriptors
(<a class="reference internal" href="#descriptors"><em>Implementing Descriptors</em></a>) for each variable name.  As a result, class attributes
cannot be used to set default values for instance variables defined by
<em>__slots__</em>; otherwise, the class attribute would overwrite the descriptor
assignment.</li>
<li>The action of a <em>__slots__</em> declaration is limited to the class where it is
defined.  As a result, subclasses will have a <em>__dict__</em> unless they also define
<em>__slots__</em> (which must only contain names of any <em>additional</em> slots).</li>
<li>If a class defines a slot also defined in a base class, the instance variable
defined by the base class slot is inaccessible (except by retrieving its
descriptor directly from the base class). This renders the meaning of the
program undefined.  In the future, a check may be added to prevent this.</li>
<li>Nonempty <em>__slots__</em> does not work for classes derived from &#8220;variable-length&#8221;
built-in types such as <a class="reference internal" href="../library/functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a>, <a class="reference internal" href="../library/functions.html#bytes" title="bytes"><tt class="xref py py-class docutils literal"><span class="pre">bytes</span></tt></a> and <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><tt class="xref py py-class docutils literal"><span class="pre">tuple</span></tt></a>.</li>
<li>Any non-string iterable may be assigned to <em>__slots__</em>. Mappings may also be
used; however, in the future, special meaning may be assigned to the values
corresponding to each key.</li>
<li><em>__class__</em> assignment works only if both classes have the same <em>__slots__</em>.</li>
</ul>
</div>
</div>
</div>
<div class="section" id="customizing-class-creation">
<span id="metaclasses"></span><h3>3.3.3. Customizing class creation<a class="headerlink" href="#customizing-class-creation" title="Permalink to this headline">¶</a></h3>
<p>By default, classes are constructed using <a class="reference internal" href="../library/functions.html#type" title="type"><tt class="xref py py-func docutils literal"><span class="pre">type()</span></tt></a>. The class body is
executed in a new namespace and the class name is bound locally to the
result of <tt class="docutils literal"><span class="pre">type(name,</span> <span class="pre">bases,</span> <span class="pre">namespace)</span></tt>.</p>
<p>The class creation process can be customised by passing the <tt class="docutils literal"><span class="pre">metaclass</span></tt>
keyword argument in the class definition line, or by inheriting from an
existing class that included such an argument. In the following example,
both <tt class="docutils literal"><span class="pre">MyClass</span></tt> and <tt class="docutils literal"><span class="pre">MySubclass</span></tt> are instances of <tt class="docutils literal"><span class="pre">Meta</span></tt>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Meta</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">Meta</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">MySubclass</span><span class="p">(</span><span class="n">MyClass</span><span class="p">):</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>Any other keyword arguments that are specified in the class definition are
passed through to all metaclass operations described below.</p>
<p>When a class definition is executed, the following steps occur:</p>
<ul class="simple">
<li>the appropriate metaclass is determined</li>
<li>the class namespace is prepared</li>
<li>the class body is executed</li>
<li>the class object is created</li>
</ul>
<div class="section" id="determining-the-appropriate-metaclass">
<h4>3.3.3.1. Determining the appropriate metaclass<a class="headerlink" href="#determining-the-appropriate-metaclass" title="Permalink to this headline">¶</a></h4>
<p>The appropriate metaclass for a class definition is determined as follows:</p>
<ul class="simple">
<li>if no bases and no explicit metaclass are given, then <a class="reference internal" href="../library/functions.html#type" title="type"><tt class="xref py py-func docutils literal"><span class="pre">type()</span></tt></a> is used</li>
<li>if an explicit metaclass is given and it is <em>not</em> an instance of
<a class="reference internal" href="../library/functions.html#type" title="type"><tt class="xref py py-func docutils literal"><span class="pre">type()</span></tt></a>, then it is used directly as the metaclass</li>
<li>if an instance of <a class="reference internal" href="../library/functions.html#type" title="type"><tt class="xref py py-func docutils literal"><span class="pre">type()</span></tt></a> is given as the explicit metaclass, or
bases are defined, then the most derived metaclass is used</li>
</ul>
<p>The most derived metaclass is selected from the explicitly specified
metaclass (if any) and the metaclasses (i.e. <tt class="docutils literal"><span class="pre">type(cls)</span></tt>) of all specified
base classes. The most derived metaclass is one which is a subtype of <em>all</em>
of these candidate metaclasses. If none of the candidate metaclasses meets
that criterion, then the class definition will fail with <tt class="docutils literal"><span class="pre">TypeError</span></tt>.</p>
</div>
<div class="section" id="preparing-the-class-namespace">
<span id="prepare"></span><h4>3.3.3.2. Preparing the class namespace<a class="headerlink" href="#preparing-the-class-namespace" title="Permalink to this headline">¶</a></h4>
<p>Once the appropriate metaclass has been identified, then the class namespace
is prepared. If the metaclass has a <tt class="docutils literal"><span class="pre">__prepare__</span></tt> attribute, it is called
as <tt class="docutils literal"><span class="pre">namespace</span> <span class="pre">=</span> <span class="pre">metaclass.__prepare__(name,</span> <span class="pre">bases,</span> <span class="pre">**kwds)</span></tt> (where the
additional keyword arguments, if any, come from the class definition).</p>
<p>If the metaclass has no <tt class="docutils literal"><span class="pre">__prepare__</span></tt> attribute, then the class namespace
is initialised as an empty <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><tt class="xref py py-func docutils literal"><span class="pre">dict()</span></tt></a> instance.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-76"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-3115"><strong>PEP 3115</strong></a> - Metaclasses in Python 3000</dt>
<dd>Introduced the <tt class="docutils literal"><span class="pre">__prepare__</span></tt> namespace hook</dd>
</dl>
</div>
</div>
<div class="section" id="executing-the-class-body">
<h4>3.3.3.3. Executing the class body<a class="headerlink" href="#executing-the-class-body" title="Permalink to this headline">¶</a></h4>
<p>The class body is executed (approximately) as
<tt class="docutils literal"><span class="pre">exec(body,</span> <span class="pre">globals(),</span> <span class="pre">namespace)</span></tt>. The key difference from a normal
call to <a class="reference internal" href="../library/functions.html#exec" title="exec"><tt class="xref py py-func docutils literal"><span class="pre">exec()</span></tt></a> is that lexical scoping allows the class body (including
any methods) to reference names from the current and outer scopes when the
class definition occurs inside a function.</p>
<p>However, even when the class definition occurs inside the function, methods
defined inside the class still cannot see names defined at the class scope.
Class variables must be accessed through the first parameter of instance or
class methods, and cannot be accessed at all from static methods.</p>
</div>
<div class="section" id="creating-the-class-object">
<h4>3.3.3.4. Creating the class object<a class="headerlink" href="#creating-the-class-object" title="Permalink to this headline">¶</a></h4>
<p>Once the class namespace has been populated by executing the class body,
the class object is created by calling
<tt class="docutils literal"><span class="pre">metaclass(name,</span> <span class="pre">bases,</span> <span class="pre">namespace,</span> <span class="pre">**kwds)</span></tt> (the additional keywords
passed here are the same as those passed to <tt class="docutils literal"><span class="pre">__prepare__</span></tt>).</p>
<p>This class object is the one that will be referenced by the zero-argument
form of <a class="reference internal" href="../library/functions.html#super" title="super"><tt class="xref py py-func docutils literal"><span class="pre">super()</span></tt></a>. <tt class="docutils literal"><span class="pre">__class__</span></tt> is an implicit closure reference
created by the compiler if any methods in a class body refer to either
<tt class="docutils literal"><span class="pre">__class__</span></tt> or <tt class="docutils literal"><span class="pre">super</span></tt>. This allows the zero argument form of
<a class="reference internal" href="../library/functions.html#super" title="super"><tt class="xref py py-func docutils literal"><span class="pre">super()</span></tt></a> to correctly identify the class being defined based on
lexical scoping, while the class or instance that was used to make the
current call is identified based on the first argument passed to the method.</p>
<p>After the class object is created, it is passed to the class decorators
included in the class definition (if any) and the resulting object is bound
in the local namespace as the defined class.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-77"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-3135"><strong>PEP 3135</strong></a> - New super</dt>
<dd>Describes the implicit <tt class="docutils literal"><span class="pre">__class__</span></tt> closure reference</dd>
</dl>
</div>
</div>
<div class="section" id="metaclass-example">
<h4>3.3.3.5. Metaclass example<a class="headerlink" href="#metaclass-example" title="Permalink to this headline">¶</a></h4>
<p>The potential uses for metaclasses are boundless. Some ideas that have been
explored include logging, interface checking, automatic delegation, automatic
property creation, proxies, frameworks, and automatic resource
locking/synchronization.</p>
<p>Here is an example of a metaclass that uses an <a class="reference internal" href="../library/collections.html#collections.OrderedDict" title="collections.OrderedDict"><tt class="xref py py-class docutils literal"><span class="pre">collections.OrderedDict</span></tt></a>
to remember the order that class variables are defined:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">class</span> <span class="nc">OrderedClass</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>

     <span class="nd">@classmethod</span>
     <span class="k">def</span> <span class="nf">__prepare__</span><span class="p">(</span><span class="n">metacls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">collections</span><span class="o">.</span><span class="n">OrderedDict</span><span class="p">()</span>

     <span class="k">def</span> <span class="nf">__new__</span><span class="p">(</span><span class="n">cls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">namespace</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
        <span class="n">result</span> <span class="o">=</span> <span class="nb">type</span><span class="o">.</span><span class="n">__new__</span><span class="p">(</span><span class="n">cls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="nb">dict</span><span class="p">(</span><span class="n">namespace</span><span class="p">))</span>
        <span class="n">result</span><span class="o">.</span><span class="n">members</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">namespace</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">result</span>

<span class="k">class</span> <span class="nc">A</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">OrderedClass</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">one</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">pass</span>
    <span class="k">def</span> <span class="nf">two</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">pass</span>
    <span class="k">def</span> <span class="nf">three</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">pass</span>
    <span class="k">def</span> <span class="nf">four</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">pass</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">A</span><span class="o">.</span><span class="n">members</span>
<span class="p">(</span><span class="s">&#39;__module__&#39;</span><span class="p">,</span> <span class="s">&#39;one&#39;</span><span class="p">,</span> <span class="s">&#39;two&#39;</span><span class="p">,</span> <span class="s">&#39;three&#39;</span><span class="p">,</span> <span class="s">&#39;four&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>When the class definition for <em>A</em> gets executed, the process begins with
calling the metaclass&#8217;s <tt class="xref py py-meth docutils literal"><span class="pre">__prepare__()</span></tt> method which returns an empty
<a class="reference internal" href="../library/collections.html#collections.OrderedDict" title="collections.OrderedDict"><tt class="xref py py-class docutils literal"><span class="pre">collections.OrderedDict</span></tt></a>.  That mapping records the methods and
attributes of <em>A</em> as they are defined within the body of the class statement.
Once those definitions are executed, the ordered dictionary is fully populated
and the metaclass&#8217;s <a class="reference internal" href="#object.__new__" title="object.__new__"><tt class="xref py py-meth docutils literal"><span class="pre">__new__()</span></tt></a> method gets invoked.  That method builds
the new type and it saves the ordered dictionary keys in an attribute
called <tt class="docutils literal"><span class="pre">members</span></tt>.</p>
</div>
</div>
<div class="section" id="customizing-instance-and-subclass-checks">
<h3>3.3.4. Customizing instance and subclass checks<a class="headerlink" href="#customizing-instance-and-subclass-checks" title="Permalink to this headline">¶</a></h3>
<p>The following methods are used to override the default behavior of the
<a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><tt class="xref py py-func docutils literal"><span class="pre">isinstance()</span></tt></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><tt class="xref py py-func docutils literal"><span class="pre">issubclass()</span></tt></a> built-in functions.</p>
<p>In particular, the metaclass <a class="reference internal" href="../library/abc.html#abc.ABCMeta" title="abc.ABCMeta"><tt class="xref py py-class docutils literal"><span class="pre">abc.ABCMeta</span></tt></a> implements these methods in
order to allow the addition of Abstract Base Classes (ABCs) as &#8220;virtual base
classes&#8221; to any class or type (including built-in types), including other
ABCs.</p>
<dl class="method">
<dt id="class.__instancecheck__">
<tt class="descclassname">class.</tt><tt class="descname">__instancecheck__</tt><big>(</big><em>self</em>, <em>instance</em><big>)</big><a class="headerlink" href="#class.__instancecheck__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>instance</em> should be considered a (direct or indirect)
instance of <em>class</em>. If defined, called to implement <tt class="docutils literal"><span class="pre">isinstance(instance,</span>
<span class="pre">class)</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="class.__subclasscheck__">
<tt class="descclassname">class.</tt><tt class="descname">__subclasscheck__</tt><big>(</big><em>self</em>, <em>subclass</em><big>)</big><a class="headerlink" href="#class.__subclasscheck__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>subclass</em> should be considered a (direct or indirect)
subclass of <em>class</em>.  If defined, called to implement <tt class="docutils literal"><span class="pre">issubclass(subclass,</span>
<span class="pre">class)</span></tt>.</p>
</dd></dl>

<p>Note that these methods are looked up on the type (metaclass) of a class.  They
cannot be defined as class methods in the actual class.  This is consistent with
the lookup of special methods that are called on instances, only in this
case the instance is itself a class.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-78"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a> - Introducing Abstract Base Classes</dt>
<dd>Includes the specification for customizing <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><tt class="xref py py-func docutils literal"><span class="pre">isinstance()</span></tt></a> and
<a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><tt class="xref py py-func docutils literal"><span class="pre">issubclass()</span></tt></a> behavior through <a class="reference internal" href="#class.__instancecheck__" title="class.__instancecheck__"><tt class="xref py py-meth docutils literal"><span class="pre">__instancecheck__()</span></tt></a> and
<a class="reference internal" href="#class.__subclasscheck__" title="class.__subclasscheck__"><tt class="xref py py-meth docutils literal"><span class="pre">__subclasscheck__()</span></tt></a>, with motivation for this functionality
in the context of adding Abstract Base Classes (see the <a class="reference internal" href="../library/abc.html#module-abc" title="abc: Abstract base classes according to PEP 3119."><tt class="xref py py-mod docutils literal"><span class="pre">abc</span></tt></a>
module) to the language.</dd>
</dl>
</div>
</div>
<div class="section" id="emulating-callable-objects">
<span id="callable-types"></span><h3>3.3.5. Emulating callable objects<a class="headerlink" href="#emulating-callable-objects" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="object.__call__">
<tt class="descclassname">object.</tt><tt class="descname">__call__</tt><big>(</big><em>self</em><span class="optional">[</span>, <em>args...</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#object.__call__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-79">Called when the instance is &#8220;called&#8221; as a function; if this method is defined,
<tt class="docutils literal"><span class="pre">x(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></tt> is a shorthand for <tt class="docutils literal"><span class="pre">x.__call__(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></tt>.</p>
</dd></dl>

</div>
<div class="section" id="emulating-container-types">
<span id="sequence-types"></span><h3>3.3.6. Emulating container types<a class="headerlink" href="#emulating-container-types" title="Permalink to this headline">¶</a></h3>
<p>The following methods can be defined to implement container objects.  Containers
usually are sequences (such as lists or tuples) or mappings (like dictionaries),
but can represent other containers as well.  The first set of methods is used
either to emulate a sequence or to emulate a mapping; the difference is that for
a sequence, the allowable keys should be the integers <em>k</em> for which <tt class="docutils literal"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">k</span> <span class="pre">&lt;</span>
<span class="pre">N</span></tt> where <em>N</em> is the length of the sequence, or slice objects, which define a
range of items.  It is also recommended that mappings provide the methods
<tt class="xref py py-meth docutils literal"><span class="pre">keys()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">values()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">items()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">clear()</span></tt>,
<tt class="xref py py-meth docutils literal"><span class="pre">setdefault()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">pop()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">popitem()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">copy()</span></tt>, and
<tt class="xref py py-meth docutils literal"><span class="pre">update()</span></tt> behaving similar to those for Python&#8217;s standard dictionary
objects.  The <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><tt class="xref py py-mod docutils literal"><span class="pre">collections</span></tt></a> module provides a
<a class="reference internal" href="../library/collections.abc.html#collections.abc.MutableMapping" title="collections.abc.MutableMapping"><tt class="xref py py-class docutils literal"><span class="pre">MutableMapping</span></tt></a>
abstract base class to help create those methods from a base set of
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>, <a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__setitem__()</span></tt></a>, <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__delitem__()</span></tt></a>, and <tt class="xref py py-meth docutils literal"><span class="pre">keys()</span></tt>.
Mutable sequences should provide methods <tt class="xref py py-meth docutils literal"><span class="pre">append()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">count()</span></tt>,
<tt class="xref py py-meth docutils literal"><span class="pre">index()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">extend()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">insert()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">pop()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">remove()</span></tt>,
<tt class="xref py py-meth docutils literal"><span class="pre">reverse()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt>, like Python standard list objects.  Finally,
sequence types should implement addition (meaning concatenation) and
multiplication (meaning repetition) by defining the methods <a class="reference internal" href="#object.__add__" title="object.__add__"><tt class="xref py py-meth docutils literal"><span class="pre">__add__()</span></tt></a>,
<a class="reference internal" href="#object.__radd__" title="object.__radd__"><tt class="xref py py-meth docutils literal"><span class="pre">__radd__()</span></tt></a>, <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><tt class="xref py py-meth docutils literal"><span class="pre">__iadd__()</span></tt></a>, <a class="reference internal" href="#object.__mul__" title="object.__mul__"><tt class="xref py py-meth docutils literal"><span class="pre">__mul__()</span></tt></a>, <a class="reference internal" href="#object.__rmul__" title="object.__rmul__"><tt class="xref py py-meth docutils literal"><span class="pre">__rmul__()</span></tt></a> and
<a class="reference internal" href="#object.__imul__" title="object.__imul__"><tt class="xref py py-meth docutils literal"><span class="pre">__imul__()</span></tt></a> described below; they should not define other numerical
operators.  It is recommended that both mappings and sequences implement the
<a class="reference internal" href="#object.__contains__" title="object.__contains__"><tt class="xref py py-meth docutils literal"><span class="pre">__contains__()</span></tt></a> method to allow efficient use of the <tt class="docutils literal"><span class="pre">in</span></tt> operator; for
mappings, <tt class="docutils literal"><span class="pre">in</span></tt> should search the mapping&#8217;s keys; for sequences, it should
search through the values.  It is further recommended that both mappings and
sequences implement the <a class="reference internal" href="#object.__iter__" title="object.__iter__"><tt class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></tt></a> method to allow efficient iteration
through the container; for mappings, <a class="reference internal" href="#object.__iter__" title="object.__iter__"><tt class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></tt></a> should be the same as
<tt class="xref py py-meth docutils literal"><span class="pre">keys()</span></tt>; for sequences, it should iterate through the values.</p>
<dl class="method">
<dt id="object.__len__">
<tt class="descclassname">object.</tt><tt class="descname">__len__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__len__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-80">Called to implement the built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><tt class="xref py py-func docutils literal"><span class="pre">len()</span></tt></a>.  Should return the length
of the object, an integer <tt class="docutils literal"><span class="pre">&gt;=</span></tt> 0.  Also, an object that doesn&#8217;t define a
<a class="reference internal" href="#object.__bool__" title="object.__bool__"><tt class="xref py py-meth docutils literal"><span class="pre">__bool__()</span></tt></a> method and whose <a class="reference internal" href="#object.__len__" title="object.__len__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></a> method returns zero is
considered to be false in a Boolean context.</p>
</dd></dl>

<dl class="method">
<dt id="object.__length_hint__">
<tt class="descclassname">object.</tt><tt class="descname">__length_hint__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__length_hint__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement <a class="reference internal" href="../library/operator.html#operator.length_hint" title="operator.length_hint"><tt class="xref py py-func docutils literal"><span class="pre">operator.length_hint()</span></tt></a>. Should return an estimated
length for the object (which may be greater or less than the actual length).
The length must be an integer <tt class="docutils literal"><span class="pre">&gt;=</span></tt> 0. This method is purely an
optimization and is never required for correctness.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.4.</span></p>
</div>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Slicing is done exclusively with the following three methods.  A call like</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="n">b</span>
</pre></div>
</div>
<p>is translated to</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">a</span><span class="p">[</span><span class="nb">slice</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="k">None</span><span class="p">)]</span> <span class="o">=</span> <span class="n">b</span>
</pre></div>
</div>
<p class="last">and so forth.  Missing slice items are always filled in with <tt class="docutils literal"><span class="pre">None</span></tt>.</p>
</div>
<dl class="method">
<dt id="object.__getitem__">
<tt class="descclassname">object.</tt><tt class="descname">__getitem__</tt><big>(</big><em>self</em>, <em>key</em><big>)</big><a class="headerlink" href="#object.__getitem__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-81">Called to implement evaluation of <tt class="docutils literal"><span class="pre">self[key]</span></tt>. For sequence types, the
accepted keys should be integers and slice objects.  Note that the special
interpretation of negative indexes (if the class wishes to emulate a sequence
type) is up to the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> method. If <em>key</em> is of an inappropriate
type, <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> may be raised; if of a value outside the set of indexes
for the sequence (after any special interpretation of negative values),
<a class="reference internal" href="../library/exceptions.html#IndexError" title="IndexError"><tt class="xref py py-exc docutils literal"><span class="pre">IndexError</span></tt></a> should be raised. For mapping types, if <em>key</em> is missing (not
in the container), <a class="reference internal" href="../library/exceptions.html#KeyError" title="KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> should be raised.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> loops expect that an <a class="reference internal" href="../library/exceptions.html#IndexError" title="IndexError"><tt class="xref py py-exc docutils literal"><span class="pre">IndexError</span></tt></a> will be raised for illegal
indexes to allow proper detection of the end of the sequence.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__missing__">
<tt class="descclassname">object.</tt><tt class="descname">__missing__</tt><big>(</big><em>self</em>, <em>key</em><big>)</big><a class="headerlink" href="#object.__missing__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called by <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a>.<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> to implement <tt class="docutils literal"><span class="pre">self[key]</span></tt> for dict subclasses
when key is not in the dictionary.</p>
</dd></dl>

<dl class="method">
<dt id="object.__setitem__">
<tt class="descclassname">object.</tt><tt class="descname">__setitem__</tt><big>(</big><em>self</em>, <em>key</em>, <em>value</em><big>)</big><a class="headerlink" href="#object.__setitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement assignment to <tt class="docutils literal"><span class="pre">self[key]</span></tt>.  Same note as for
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>.  This should only be implemented for mappings if the
objects support changes to the values for keys, or if new keys can be added, or
for sequences if elements can be replaced.  The same exceptions should be raised
for improper <em>key</em> values as for the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="object.__delitem__">
<tt class="descclassname">object.</tt><tt class="descname">__delitem__</tt><big>(</big><em>self</em>, <em>key</em><big>)</big><a class="headerlink" href="#object.__delitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement deletion of <tt class="docutils literal"><span class="pre">self[key]</span></tt>.  Same note as for
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>.  This should only be implemented for mappings if the
objects support removal of keys, or for sequences if elements can be removed
from the sequence.  The same exceptions should be raised for improper <em>key</em>
values as for the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="object.__iter__">
<tt class="descclassname">object.</tt><tt class="descname">__iter__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__iter__" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called when an iterator is required for a container. This method
should return a new iterator object that can iterate over all the objects in the
container.  For mappings, it should iterate over the keys of the container.</p>
<p>Iterator objects also need to implement this method; they are required to return
themselves.  For more information on iterator objects, see <a class="reference internal" href="../library/stdtypes.html#typeiter"><em>Iterator Types</em></a>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__reversed__">
<tt class="descclassname">object.</tt><tt class="descname">__reversed__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__reversed__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called (if present) by the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><tt class="xref py py-func docutils literal"><span class="pre">reversed()</span></tt></a> built-in to implement
reverse iteration.  It should return a new iterator object that iterates
over all the objects in the container in reverse order.</p>
<p>If the <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><tt class="xref py py-meth docutils literal"><span class="pre">__reversed__()</span></tt></a> method is not provided, the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><tt class="xref py py-func docutils literal"><span class="pre">reversed()</span></tt></a>
built-in will fall back to using the sequence protocol (<a class="reference internal" href="#object.__len__" title="object.__len__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></a> and
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>).  Objects that support the sequence protocol should
only provide <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><tt class="xref py py-meth docutils literal"><span class="pre">__reversed__()</span></tt></a> if they can provide an implementation
that is more efficient than the one provided by <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><tt class="xref py py-func docutils literal"><span class="pre">reversed()</span></tt></a>.</p>
</dd></dl>

<p>The membership test operators (<a class="reference internal" href="expressions.html#in"><tt class="xref std std-keyword docutils literal"><span class="pre">in</span></tt></a> and <a class="reference internal" href="expressions.html#not-in"><tt class="xref std std-keyword docutils literal"><span class="pre">not</span> <span class="pre">in</span></tt></a>) are normally
implemented as an iteration through a sequence.  However, container objects can
supply the following special method with a more efficient implementation, which
also does not require the object be a sequence.</p>
<dl class="method">
<dt id="object.__contains__">
<tt class="descclassname">object.</tt><tt class="descname">__contains__</tt><big>(</big><em>self</em>, <em>item</em><big>)</big><a class="headerlink" href="#object.__contains__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement membership test operators.  Should return true if <em>item</em>
is in <em>self</em>, false otherwise.  For mapping objects, this should consider the
keys of the mapping rather than the values or the key-item pairs.</p>
<p>For objects that don&#8217;t define <a class="reference internal" href="#object.__contains__" title="object.__contains__"><tt class="xref py py-meth docutils literal"><span class="pre">__contains__()</span></tt></a>, the membership test first
tries iteration via <a class="reference internal" href="#object.__iter__" title="object.__iter__"><tt class="xref py py-meth docutils literal"><span class="pre">__iter__()</span></tt></a>, then the old sequence iteration
protocol via <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>, see <a class="reference internal" href="expressions.html#membership-test-details"><em>this section in the language
reference</em></a>.</p>
</dd></dl>

</div>
<div class="section" id="emulating-numeric-types">
<span id="numeric-types"></span><h3>3.3.7. Emulating numeric types<a class="headerlink" href="#emulating-numeric-types" title="Permalink to this headline">¶</a></h3>
<p>The following methods can be defined to emulate numeric objects. Methods
corresponding to operations that are not supported by the particular kind of
number implemented (e.g., bitwise operations for non-integral numbers) should be
left undefined.</p>
<dl class="method">
<dt id="object.__add__">
<tt class="descclassname">object.</tt><tt class="descname">__add__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__add__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__sub__">
<tt class="descclassname">object.</tt><tt class="descname">__sub__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__sub__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__mul__">
<tt class="descclassname">object.</tt><tt class="descname">__mul__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__mul__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__truediv__">
<tt class="descclassname">object.</tt><tt class="descname">__truediv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__truediv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__floordiv__">
<tt class="descclassname">object.</tt><tt class="descname">__floordiv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__floordiv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__mod__">
<tt class="descclassname">object.</tt><tt class="descname">__mod__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__mod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__divmod__">
<tt class="descclassname">object.</tt><tt class="descname">__divmod__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__divmod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__pow__">
<tt class="descclassname">object.</tt><tt class="descname">__pow__</tt><big>(</big><em>self</em>, <em>other</em><span class="optional">[</span>, <em>modulo</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#object.__pow__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__lshift__">
<tt class="descclassname">object.</tt><tt class="descname">__lshift__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__lshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rshift__">
<tt class="descclassname">object.</tt><tt class="descname">__rshift__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__and__">
<tt class="descclassname">object.</tt><tt class="descname">__and__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__and__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__xor__">
<tt class="descclassname">object.</tt><tt class="descname">__xor__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__xor__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__or__">
<tt class="descclassname">object.</tt><tt class="descname">__or__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__or__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-82">These methods are called to implement the binary arithmetic operations (<tt class="docutils literal"><span class="pre">+</span></tt>,
<tt class="docutils literal"><span class="pre">-</span></tt>, <tt class="docutils literal"><span class="pre">*</span></tt>, <tt class="docutils literal"><span class="pre">/</span></tt>, <tt class="docutils literal"><span class="pre">//</span></tt>, <tt class="docutils literal"><span class="pre">%</span></tt>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><tt class="xref py py-func docutils literal"><span class="pre">divmod()</span></tt></a>, <a class="reference internal" href="../library/functions.html#pow" title="pow"><tt class="xref py py-func docutils literal"><span class="pre">pow()</span></tt></a>, <tt class="docutils literal"><span class="pre">**</span></tt>, <tt class="docutils literal"><span class="pre">&lt;&lt;</span></tt>,
<tt class="docutils literal"><span class="pre">&gt;&gt;</span></tt>, <tt class="docutils literal"><span class="pre">&amp;</span></tt>, <tt class="docutils literal"><span class="pre">^</span></tt>, <tt class="docutils literal"><span class="pre">|</span></tt>).  For instance, to evaluate the expression
<tt class="docutils literal"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></tt>, where <em>x</em> is an instance of a class that has an <a class="reference internal" href="#object.__add__" title="object.__add__"><tt class="xref py py-meth docutils literal"><span class="pre">__add__()</span></tt></a>
method, <tt class="docutils literal"><span class="pre">x.__add__(y)</span></tt> is called.  The <a class="reference internal" href="#object.__divmod__" title="object.__divmod__"><tt class="xref py py-meth docutils literal"><span class="pre">__divmod__()</span></tt></a> method should be the
equivalent to using <a class="reference internal" href="#object.__floordiv__" title="object.__floordiv__"><tt class="xref py py-meth docutils literal"><span class="pre">__floordiv__()</span></tt></a> and <a class="reference internal" href="#object.__mod__" title="object.__mod__"><tt class="xref py py-meth docutils literal"><span class="pre">__mod__()</span></tt></a>; it should not be
related to <a class="reference internal" href="#object.__truediv__" title="object.__truediv__"><tt class="xref py py-meth docutils literal"><span class="pre">__truediv__()</span></tt></a>.  Note that <a class="reference internal" href="#object.__pow__" title="object.__pow__"><tt class="xref py py-meth docutils literal"><span class="pre">__pow__()</span></tt></a> should be defined
to accept an optional third argument if the ternary version of the built-in
<a class="reference internal" href="../library/functions.html#pow" title="pow"><tt class="xref py py-func docutils literal"><span class="pre">pow()</span></tt></a> function is to be supported.</p>
<p>If one of those methods does not support the operation with the supplied
arguments, it should return <tt class="docutils literal"><span class="pre">NotImplemented</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__radd__">
<tt class="descclassname">object.</tt><tt class="descname">__radd__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__radd__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rsub__">
<tt class="descclassname">object.</tt><tt class="descname">__rsub__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rsub__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rmul__">
<tt class="descclassname">object.</tt><tt class="descname">__rmul__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rmul__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rtruediv__">
<tt class="descclassname">object.</tt><tt class="descname">__rtruediv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rtruediv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rfloordiv__">
<tt class="descclassname">object.</tt><tt class="descname">__rfloordiv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rfloordiv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rmod__">
<tt class="descclassname">object.</tt><tt class="descname">__rmod__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rmod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rdivmod__">
<tt class="descclassname">object.</tt><tt class="descname">__rdivmod__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rdivmod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rpow__">
<tt class="descclassname">object.</tt><tt class="descname">__rpow__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rpow__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rlshift__">
<tt class="descclassname">object.</tt><tt class="descname">__rlshift__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rlshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rrshift__">
<tt class="descclassname">object.</tt><tt class="descname">__rrshift__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rrshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rand__">
<tt class="descclassname">object.</tt><tt class="descname">__rand__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rand__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rxor__">
<tt class="descclassname">object.</tt><tt class="descname">__rxor__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__rxor__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ror__">
<tt class="descclassname">object.</tt><tt class="descname">__ror__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__ror__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-83">These methods are called to implement the binary arithmetic operations (<tt class="docutils literal"><span class="pre">+</span></tt>,
<tt class="docutils literal"><span class="pre">-</span></tt>, <tt class="docutils literal"><span class="pre">*</span></tt>, <tt class="docutils literal"><span class="pre">/</span></tt>, <tt class="docutils literal"><span class="pre">//</span></tt>, <tt class="docutils literal"><span class="pre">%</span></tt>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><tt class="xref py py-func docutils literal"><span class="pre">divmod()</span></tt></a>, <a class="reference internal" href="../library/functions.html#pow" title="pow"><tt class="xref py py-func docutils literal"><span class="pre">pow()</span></tt></a>, <tt class="docutils literal"><span class="pre">**</span></tt>,
<tt class="docutils literal"><span class="pre">&lt;&lt;</span></tt>, <tt class="docutils literal"><span class="pre">&gt;&gt;</span></tt>, <tt class="docutils literal"><span class="pre">&amp;</span></tt>, <tt class="docutils literal"><span class="pre">^</span></tt>, <tt class="docutils literal"><span class="pre">|</span></tt>) with reflected (swapped) operands.
These functions are only called if the left operand does not support the
corresponding operation and the operands are of different types. <a class="footnote-reference" href="#id5" id="id3">[2]</a>  For
instance, to evaluate the expression <tt class="docutils literal"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">y</span></tt>, where <em>y</em> is an instance of
a class that has an <a class="reference internal" href="#object.__rsub__" title="object.__rsub__"><tt class="xref py py-meth docutils literal"><span class="pre">__rsub__()</span></tt></a> method, <tt class="docutils literal"><span class="pre">y.__rsub__(x)</span></tt> is called if
<tt class="docutils literal"><span class="pre">x.__sub__(y)</span></tt> returns <em>NotImplemented</em>.</p>
<p id="index-84">Note that ternary <a class="reference internal" href="../library/functions.html#pow" title="pow"><tt class="xref py py-func docutils literal"><span class="pre">pow()</span></tt></a> will not try calling <a class="reference internal" href="#object.__rpow__" title="object.__rpow__"><tt class="xref py py-meth docutils literal"><span class="pre">__rpow__()</span></tt></a> (the
coercion rules would become too complicated).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If the right operand&#8217;s type is a subclass of the left operand&#8217;s type and that
subclass provides the reflected method for the operation, this method will be
called before the left operand&#8217;s non-reflected method.  This behavior allows
subclasses to override their ancestors&#8217; operations.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__iadd__">
<tt class="descclassname">object.</tt><tt class="descname">__iadd__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__iadd__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__isub__">
<tt class="descclassname">object.</tt><tt class="descname">__isub__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__isub__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__imul__">
<tt class="descclassname">object.</tt><tt class="descname">__imul__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__imul__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__itruediv__">
<tt class="descclassname">object.</tt><tt class="descname">__itruediv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__itruediv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ifloordiv__">
<tt class="descclassname">object.</tt><tt class="descname">__ifloordiv__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__ifloordiv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__imod__">
<tt class="descclassname">object.</tt><tt class="descname">__imod__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__imod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ipow__">
<tt class="descclassname">object.</tt><tt class="descname">__ipow__</tt><big>(</big><em>self</em>, <em>other</em><span class="optional">[</span>, <em>modulo</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#object.__ipow__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ilshift__">
<tt class="descclassname">object.</tt><tt class="descname">__ilshift__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__ilshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__irshift__">
<tt class="descclassname">object.</tt><tt class="descname">__irshift__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__irshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__iand__">
<tt class="descclassname">object.</tt><tt class="descname">__iand__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__iand__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ixor__">
<tt class="descclassname">object.</tt><tt class="descname">__ixor__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__ixor__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ior__">
<tt class="descclassname">object.</tt><tt class="descname">__ior__</tt><big>(</big><em>self</em>, <em>other</em><big>)</big><a class="headerlink" href="#object.__ior__" title="Permalink to this definition">¶</a></dt>
<dd><p>These methods are called to implement the augmented arithmetic assignments
(<tt class="docutils literal"><span class="pre">+=</span></tt>, <tt class="docutils literal"><span class="pre">-=</span></tt>, <tt class="docutils literal"><span class="pre">*=</span></tt>, <tt class="docutils literal"><span class="pre">/=</span></tt>, <tt class="docutils literal"><span class="pre">//=</span></tt>, <tt class="docutils literal"><span class="pre">%=</span></tt>, <tt class="docutils literal"><span class="pre">**=</span></tt>, <tt class="docutils literal"><span class="pre">&lt;&lt;=</span></tt>, <tt class="docutils literal"><span class="pre">&gt;&gt;=</span></tt>,
<tt class="docutils literal"><span class="pre">&amp;=</span></tt>, <tt class="docutils literal"><span class="pre">^=</span></tt>, <tt class="docutils literal"><span class="pre">|=</span></tt>).  These methods should attempt to do the operation
in-place (modifying <em>self</em>) and return the result (which could be, but does
not have to be, <em>self</em>).  If a specific method is not defined, the augmented
assignment falls back to the normal methods.  For instance, if <em>x</em> is an
instance of a class with an <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><tt class="xref py py-meth docutils literal"><span class="pre">__iadd__()</span></tt></a> method, <tt class="docutils literal"><span class="pre">x</span> <span class="pre">+=</span> <span class="pre">y</span></tt> is equivalent
to <tt class="docutils literal"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">x.__iadd__(y)</span></tt> . Otherwise, <tt class="docutils literal"><span class="pre">x.__add__(y)</span></tt> and <tt class="docutils literal"><span class="pre">y.__radd__(x)</span></tt>
are considered, as with the evaluation of <tt class="docutils literal"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></tt>. In certain situations,
augmented assignment can result in unexpected errors (see
<a class="reference internal" href="../faq/programming.html#faq-augmented-assignment-tuple-error"><em>Why does a_tuple[i] += [&#8216;item&#8217;] raise an exception when the addition works?</em></a>), but this behavior is in
fact part of the data model.</p>
</dd></dl>

<dl class="method">
<dt id="object.__neg__">
<tt class="descclassname">object.</tt><tt class="descname">__neg__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__neg__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__pos__">
<tt class="descclassname">object.</tt><tt class="descname">__pos__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__pos__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__abs__">
<tt class="descclassname">object.</tt><tt class="descname">__abs__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__abs__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__invert__">
<tt class="descclassname">object.</tt><tt class="descname">__invert__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__invert__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-85">Called to implement the unary arithmetic operations (<tt class="docutils literal"><span class="pre">-</span></tt>, <tt class="docutils literal"><span class="pre">+</span></tt>, <a class="reference internal" href="../library/functions.html#abs" title="abs"><tt class="xref py py-func docutils literal"><span class="pre">abs()</span></tt></a>
and <tt class="docutils literal"><span class="pre">~</span></tt>).</p>
</dd></dl>

<dl class="method">
<dt id="object.__complex__">
<tt class="descclassname">object.</tt><tt class="descname">__complex__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__complex__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__int__">
<tt class="descclassname">object.</tt><tt class="descname">__int__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__int__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__float__">
<tt class="descclassname">object.</tt><tt class="descname">__float__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__float__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__round__">
<tt class="descclassname">object.</tt><tt class="descname">__round__</tt><big>(</big><em>self</em><span class="optional">[</span>, <em>n</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#object.__round__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-86">Called to implement the built-in functions <a class="reference internal" href="../library/functions.html#complex" title="complex"><tt class="xref py py-func docutils literal"><span class="pre">complex()</span></tt></a>,
<a class="reference internal" href="../library/functions.html#int" title="int"><tt class="xref py py-func docutils literal"><span class="pre">int()</span></tt></a>, <a class="reference internal" href="../library/functions.html#float" title="float"><tt class="xref py py-func docutils literal"><span class="pre">float()</span></tt></a> and <a class="reference internal" href="../library/functions.html#round" title="round"><tt class="xref py py-func docutils literal"><span class="pre">round()</span></tt></a>.  Should return a value
of the appropriate type.</p>
</dd></dl>

<dl class="method">
<dt id="object.__index__">
<tt class="descclassname">object.</tt><tt class="descname">__index__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__index__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement <a class="reference internal" href="../library/operator.html#operator.index" title="operator.index"><tt class="xref py py-func docutils literal"><span class="pre">operator.index()</span></tt></a>, and whenever Python needs to
losslessly convert the numeric object to an integer object (such as in
slicing, or in the built-in <a class="reference internal" href="../library/functions.html#bin" title="bin"><tt class="xref py py-func docutils literal"><span class="pre">bin()</span></tt></a>, <a class="reference internal" href="../library/functions.html#hex" title="hex"><tt class="xref py py-func docutils literal"><span class="pre">hex()</span></tt></a> and <a class="reference internal" href="../library/functions.html#oct" title="oct"><tt class="xref py py-func docutils literal"><span class="pre">oct()</span></tt></a>
functions). Presence of this method indicates that the numeric object is
an integer type.  Must return an integer.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In order to have a coherent integer type class, when <a class="reference internal" href="#object.__index__" title="object.__index__"><tt class="xref py py-meth docutils literal"><span class="pre">__index__()</span></tt></a> is
defined <a class="reference internal" href="#object.__int__" title="object.__int__"><tt class="xref py py-meth docutils literal"><span class="pre">__int__()</span></tt></a> should also be defined, and both should return
the same value.</p>
</div>
</dd></dl>

</div>
<div class="section" id="with-statement-context-managers">
<span id="context-managers"></span><h3>3.3.8. With Statement Context Managers<a class="headerlink" href="#with-statement-context-managers" title="Permalink to this headline">¶</a></h3>
<p>A <em class="dfn">context manager</em> is an object that defines the runtime context to be
established when executing a <a class="reference internal" href="compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement. The context manager
handles the entry into, and the exit from, the desired runtime context for the
execution of the block of code.  Context managers are normally invoked using the
<a class="reference internal" href="compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement (described in section <a class="reference internal" href="compound_stmts.html#with"><em>The with statement</em></a>), but can also be
used by directly invoking their methods.</p>
<p id="index-87">Typical uses of context managers include saving and restoring various kinds of
global state, locking and unlocking resources, closing opened files, etc.</p>
<p>For more information on context managers, see <a class="reference internal" href="../library/stdtypes.html#typecontextmanager"><em>Context Manager Types</em></a>.</p>
<dl class="method">
<dt id="object.__enter__">
<tt class="descclassname">object.</tt><tt class="descname">__enter__</tt><big>(</big><em>self</em><big>)</big><a class="headerlink" href="#object.__enter__" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter the runtime context related to this object. The <a class="reference internal" href="compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement
will bind this method&#8217;s return value to the target(s) specified in the
<a class="reference internal" href="compound_stmts.html#as"><tt class="xref std std-keyword docutils literal"><span class="pre">as</span></tt></a> clause of the statement, if any.</p>
</dd></dl>

<dl class="method">
<dt id="object.__exit__">
<tt class="descclassname">object.</tt><tt class="descname">__exit__</tt><big>(</big><em>self</em>, <em>exc_type</em>, <em>exc_value</em>, <em>traceback</em><big>)</big><a class="headerlink" href="#object.__exit__" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit the runtime context related to this object. The parameters describe the
exception that caused the context to be exited. If the context was exited
without an exception, all three arguments will be <a class="reference internal" href="../library/constants.html#None" title="None"><tt class="xref py py-const docutils literal"><span class="pre">None</span></tt></a>.</p>
<p>If an exception is supplied, and the method wishes to suppress the exception
(i.e., prevent it from being propagated), it should return a true value.
Otherwise, the exception will be processed normally upon exit from this method.</p>
<p>Note that <a class="reference internal" href="#object.__exit__" title="object.__exit__"><tt class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></tt></a> methods should not reraise the passed-in exception;
this is the caller&#8217;s responsibility.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-88"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0343"><strong>PEP 0343</strong></a> - The &#8220;with&#8221; statement</dt>
<dd>The specification, background, and examples for the Python <a class="reference internal" href="compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>
statement.</dd>
</dl>
</div>
</div>
<div class="section" id="special-method-lookup">
<span id="special-lookup"></span><h3>3.3.9. Special method lookup<a class="headerlink" href="#special-method-lookup" title="Permalink to this headline">¶</a></h3>
<p>For custom classes, implicit invocations of special methods are only guaranteed
to work correctly if defined on an object&#8217;s type, not in the object&#8217;s instance
dictionary.  That behaviour is the reason why the following code raises an
exception:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">__len__</span> <span class="o">=</span> <span class="k">lambda</span><span class="p">:</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">object of type &#39;C&#39; has no len()</span>
</pre></div>
</div>
<p>The rationale behind this behaviour lies with a number of special methods such
as <a class="reference internal" href="#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> and <a class="reference internal" href="#object.__repr__" title="object.__repr__"><tt class="xref py py-meth docutils literal"><span class="pre">__repr__()</span></tt></a> that are implemented by all objects,
including type objects. If the implicit lookup of these methods used the
conventional lookup process, they would fail when invoked on the type object
itself:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="mi">1</span> <span class="o">.</span><span class="n">__hash__</span><span class="p">()</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">__hash__</span><span class="p">()</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">descriptor &#39;__hash__&#39; of &#39;int&#39; object needs an argument</span>
</pre></div>
</div>
<p>Incorrectly attempting to invoke an unbound method of a class in this way is
sometimes referred to as &#8216;metaclass confusion&#8217;, and is avoided by bypassing
the instance when looking up special methods:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">__hash__</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span><span class="o">.</span><span class="n">__hash__</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p>In addition to bypassing any instance attributes in the interest of
correctness, implicit special method lookup generally also bypasses the
<a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></tt></a> method even of the object&#8217;s metaclass:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Meta</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>        <span class="nb">print</span><span class="p">(</span><span class="s">&quot;Metaclass getattribute invoked&quot;</span><span class="p">)</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="nb">type</span><span class="o">.</span><span class="n">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">,</span> <span class="n">metaclass</span><span class="o">=</span><span class="n">Meta</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="mi">10</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>        <span class="nb">print</span><span class="p">(</span><span class="s">&quot;Class getattribute invoked&quot;</span><span class="p">)</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="nb">object</span><span class="o">.</span><span class="n">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">__len__</span><span class="p">()</span>                 <span class="c"># Explicit lookup via instance</span>
<span class="go">Class getattribute invoked</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">c</span><span class="p">)</span><span class="o">.</span><span class="n">__len__</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>          <span class="c"># Explicit lookup via type</span>
<span class="go">Metaclass getattribute invoked</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                      <span class="c"># Implicit lookup</span>
<span class="go">10</span>
</pre></div>
</div>
<p>Bypassing the <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattribute__()</span></tt></a> machinery in this fashion
provides significant scope for speed optimisations within the
interpreter, at the cost of some flexibility in the handling of
special methods (the special method <em>must</em> be set on the class
object itself in order to be consistently invoked by the interpreter).</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id4" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>It <em>is</em> possible in some cases to change an object&#8217;s type, under certain
controlled conditions. It generally isn&#8217;t a good idea though, since it can
lead to some very strange behaviour if it is handled incorrectly.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id5" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[2]</a></td><td>For operands of the same type, it is assumed that if the non-reflected method
(such as <a class="reference internal" href="#object.__add__" title="object.__add__"><tt class="xref py py-meth docutils literal"><span class="pre">__add__()</span></tt></a>) fails the operation is not supported, which is why the
reflected method is not called.</td></tr>
</tbody>
</table>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">3. Data model</a><ul>
<li><a class="reference internal" href="#objects-values-and-types">3.1. Objects, values and types</a></li>
<li><a class="reference internal" href="#the-standard-type-hierarchy">3.2. The standard type hierarchy</a></li>
<li><a class="reference internal" href="#special-method-names">3.3. Special method names</a><ul>
<li><a class="reference internal" href="#basic-customization">3.3.1. Basic customization</a></li>
<li><a class="reference internal" href="#customizing-attribute-access">3.3.2. Customizing attribute access</a><ul>
<li><a class="reference internal" href="#implementing-descriptors">3.3.2.1. Implementing Descriptors</a></li>
<li><a class="reference internal" href="#invoking-descriptors">3.3.2.2. Invoking Descriptors</a></li>
<li><a class="reference internal" href="#slots">3.3.2.3. __slots__</a><ul>
<li><a class="reference internal" href="#notes-on-using-slots">3.3.2.3.1. Notes on using <em>__slots__</em></a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#customizing-class-creation">3.3.3. Customizing class creation</a><ul>
<li><a class="reference internal" href="#determining-the-appropriate-metaclass">3.3.3.1. Determining the appropriate metaclass</a></li>
<li><a class="reference internal" href="#preparing-the-class-namespace">3.3.3.2. Preparing the class namespace</a></li>
<li><a class="reference internal" href="#executing-the-class-body">3.3.3.3. Executing the class body</a></li>
<li><a class="reference internal" href="#creating-the-class-object">3.3.3.4. Creating the class object</a></li>
<li><a class="reference internal" href="#metaclass-example">3.3.3.5. Metaclass example</a></li>
</ul>
</li>
<li><a class="reference internal" href="#customizing-instance-and-subclass-checks">3.3.4. Customizing instance and subclass checks</a></li>
<li><a class="reference internal" href="#emulating-callable-objects">3.3.5. Emulating callable objects</a></li>
<li><a class="reference internal" href="#emulating-container-types">3.3.6. Emulating container types</a></li>
<li><a class="reference internal" href="#emulating-numeric-types">3.3.7. Emulating numeric types</a></li>
<li><a class="reference internal" href="#with-statement-context-managers">3.3.8. With Statement Context Managers</a></li>
<li><a class="reference internal" href="#special-method-lookup">3.3.9. Special method lookup</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="lexical_analysis.html"
                        title="previous chapter">2. Lexical analysis</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="executionmodel.html"
                        title="next chapter">4. Execution model</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/reference/datamodel.txt"
         rel="nofollow">Show Source</a></li>
</ul>

<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="executionmodel.html" title="4. Execution model"
             >next</a> |</li>
        <li class="right" >
          <a href="lexical_analysis.html" title="2. Lexical analysis"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &raquo;</li>
        <li>
          <span class="version_switcher_placeholder">3.4.3</span>
          <a href="../index.html">Documentation</a> &raquo;
        </li>

          <li><a href="index.html" >The Python Language Reference</a> &raquo;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2015, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Aug 06, 2015.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.3.
    </div>

  </body>
</html>